﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Management;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
//using System.Linq;

namespace PIM_ATE.Electrical
{
    public partial class FrmSParam : BaseDlg
    {
        public FrmSParam(ClsDataUser user)
        {
            InitializeComponent();
            int size = 900;
            this.Size = new Size(size, size * 3 / 4);
            this.Text = "电性能测试 1.5";
            m_isLocalConfg = GDefine.IS_LOCAL_CONFIG_SPARAM;
            DEBUG_TEST = GDefine.IS_RCU_DEBUG_TEST;
            m_usrObj = user;
        }

        clsProject m_cProject;
        JcInstrument m_Instr;

        clsBaseVNA m_CInstrVNA;
        InstrSwitch m_CLoadSwitch;

        DataTable m_dtTestItem;
        DataTable m_dtShow;
        bool m_IsRun = false;
        bool m_bNeedQuit = false;
        bool m_IsVNADebug = false;
        DateTime m_iTimeStart;
        DateTime m_iTimeEnd;
        string[] m_arrShowList;

        //string m_sPartCode;
        //string m_sELECStep;
        Thread m_TestThread;
        //当前测试模式
        string type = "电性能测试";
        //调度速度
        int m_iSpeed = 0;
        //开关端口
        int m_PortCount = 8;
        //测试顺序
        int m_TestTimes = 2;
        //接线顺序
        int m_ChangeTimes = 1;
        //还原角度配置
        int m_RevertAngle;

        //功能标识
        bool IsSwitch = true;
        bool IsVNA = true;

        //复测当前项标识
        bool IsReTest = true;
        bool IsManualOffset = false;
        bool m_bRetestFlag = false;

        bool m_bTotalResult = false;
        bool m_bManualStop = true;
        const string CALREG_ALL_BAND = "N2-ALL-0.3-3000";
        string m_sCurReg = "";
        string m_sLastReg = "";

        //开关标识
        const int SwitchNeedTime = 500;

        bool m_isLocalConfg = false;
        bool DEBUG_TEST = false;
        bool m_isInitMaxAngle;

        RCUrunner m_rcuObj;
        ClsDataUser m_usrObj;

        ClsDataProduct m_productObj;
        List<clsTestItem> m_testConfig;
        List<bool> m_enableConfig;
        Dictionary<string, RCUInfo> m_dicRCUs;
        ClsDataSParamBuilder m_cTestConfigBuilder;
        Dictionary<int, JcELECDataResults> m_dicResult;
        ClsDataResultForAntennaBuilder m_resultBuilder;

        System.Threading.Timer m_time_now;

        delegate void DelContinueSetRCUIndex(ImpCtrl ctl, string sRCUIndex, int iAngle);
        List<clsTraceTest> m_Continue_lsTraceTested = new List<clsTraceTest>();//缓存换度过程的端口信息       
        AntennaType m_AntennaType = AntennaType.NUMAL;
        List<int> m_lstTestType = new List<int>();
        bool m_isTestIso = false, m_isTestAmPh = false; string m_Procode = "";
        ClsCalRecord m_CheckRecord;
        List<ClsCalRecordItem> m_lstCheckRecordItem;

        bool m_SNcheckPass;
        bool m_WavefromPass;
        bool m_RcuCalPass;
        bool m_AllTestItemPass;


        private void FrmSParam_Load(object sender, EventArgs e)
        {

            #region 设备初始化
            m_Instr = new JcInstrument();
            //先从本地读取仪表开关信息
            IniFile.SetFileName(Application.StartupPath + GDefine.PATH_VNA_INI);
            m_Instr.VNAName = IniFile.IniReadValue(GDefine.INI_SECTION_INSTR, GDefine.INI_INSTR_NAME, "");
            m_Instr.VNA_Addr = IniFile.IniReadValue(GDefine.INI_SECTION_INSTR, GDefine.INI_INSTR_ADDR, "");

            m_Instr.Switch_Type = Convert.ToInt32(IniFile.IniReadValue(GDefine.INI_SECTION_INSTR, GDefine.INI_SWITCH_TYPE, "0"));
            m_Instr.Switch_ConnPort = IniFile.IniReadValue(GDefine.INI_SECTION_INSTR, GDefine.INI_SWITCH_PORT, "");
            m_Instr.Switch_Count = Convert.ToInt32(IniFile.IniReadValue(GDefine.INI_SECTION_INSTR, GDefine.INI_SWITCH_COUNT, "8"));

            m_Instr.RCU_Type = Convert.ToInt32(IniFile.IniReadValue(GDefine.INI_SECTION_INSTR, GDefine.INI_RCU_TYPE, "0"));
            m_Instr.RCU_Addr = IniFile.IniReadValue(GDefine.INI_SECTION_INSTR, GDefine.INI_RCU_PORT, "");



            IniFile.SetFileName(System.Windows.Forms.Application.StartupPath + "\\JcDevices.ini");
            //try { ctl_main_nudSpeed.Value = Convert.ToDecimal(IniFile.IniReadValue("Settings", "RCU_Speed", "2")); }
            //catch { ctl_main_nudSpeed.Value = 2; }
            ctl_main_nudSpeed.Value = 0;
            ctl_main_nudSpeed.Enabled = true;
            //显示当前的仪表连接信息到界面
            ShowInfo();
            #endregion

            #region dgvTest初始化
            cbELECStep.SelectedIndex = 0;
            dgvTest.RowHeadersVisible = false;
            dgvTest.AllowUserToAddRows = false;
            int i = 0;
            m_arrShowList = new string[14];
            m_arrShowList[i++] = clsTestItem.chn_ParamName; //m_cTestItem.m_arrExcelHead[1];//m_dtTestItem.Columns[1].ColumnName;//参数名称
            m_arrShowList[i++] = clsTestItem.chn_Freq;
            //m_arrShowList[i++] = clsTestItem.chn_Band;
            m_arrShowList[i++] = clsTestItem.chn_TestNo;
            m_arrShowList[i++] = clsTestItem.chn_PortA_Angle;
            m_arrShowList[i++] = clsTestItem.chn_PortB_Angle;
            m_arrShowList[i++] = clsTestItem.chn_PortA_RCU;
            m_arrShowList[i++] = clsTestItem.chn_PortB_RCU;
            m_arrShowList[i++] = clsTestItem.chn_PortA;
            m_arrShowList[i++] = clsTestItem.chn_PortB;
            m_arrShowList[i++] = clsTestItem.chn_FactSpec; //m_cTestItem.m_arrExcelHead[3];//m_dtTestItem.Columns[2].ColumnName;//内控要求
            m_arrShowList[i++] = clsTestItem.chn_Value;//m_dtTestItem.Columns[m_cTestItem.iColumnNum].ColumnName;//测试值
            m_arrShowList[i++] = clsTestItem.chn_Result;//m_dtTestItem.Columns[m_cTestItem.iColumnNum + 1].ColumnName;//结果
            m_arrShowList[i++] = clsTestItem.chn_LastValue;//m_dtTestItem.Columns[m_cTestItem.iColumnNum + 2].ColumnName;//上次测试值
            m_arrShowList[i++] = clsTestItem.chn_LastResult;//m_dtTestItem.Columns[m_cTestItem.iColumnNum + 3].ColumnName;//上次结果
            //m_arrShowList[i++] = clsTestItem.chn_NowValue;
            #endregion

            #region database初始化

            initDataBaseNames();
            if (m_isLocalConfg)
            {
                btnSet.Text = "本地";
            }
            else
            {
                btnSet.Text = "刷新";
                initDataConfig();
            }

            #endregion

            //m_time_now = new System.Threading.Timer(evt_timer_tick, null, 0, 1000);

            toolStripStatusLabel2.Text = string.Format("员工号: {0}/{1}    姓名: {2}/{3}    账号类型: {4}/{5}",
                                                        m_usrObj.sUserID, m_usrObj.sUserID2, m_usrObj.sUser, m_usrObj.sUser2, m_usrObj.sRemark, m_usrObj.sRemark2);
            toolStripStatusLabel3.Text = string.Format("设备编号: {0}   管理部门: 质量", m_usrObj.sEquID);

            cbRebootStatus.SelectedIndex = 2;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            IniFile.SetFileName(System.Windows.Forms.Application.StartupPath + "\\JcDevices.ini");
            IniFile.IniWriteValue("Settings", "RCU_Speed", ctl_main_nudSpeed.Value.ToString());

            base.OnClosing(e);
        }

        private void evt_timer_tick(object sender)
        {//时间事件
            this.toolStripStatusLabel4.Text = DateTime.Now.ToShortTimeString();
        }

        private void ShowText(object obj, EventArgs e)
        {
            string str = obj as string;
            tb_Test.AppendText(str);
        }
        private void ShowCursor(object obj, EventArgs e)
        {
            tbProSN.Focus();
        }

        private void ShowTestOff(object obj, EventArgs e)
        {
            string sFilePath = System.Windows.Forms.Application.StartupPath + "\\LogMessage";
            if (!Directory.Exists(sFilePath))
            {
                Directory.CreateDirectory(sFilePath);
            }

            string sFileName = tbProSN.Text + "Sparam" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            sFileName = sFilePath + "\\" + sFileName; //文件的绝对路径
            FileStream fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(tb_Test.Text);
            sw.Close();
            fs.Close();

            //progressBar1.Value = progressBar1.Maximum;
            setEnable(true);
            BtnInstr.Enabled = true;
            //btnReport.Enabled = true;
            m_IsRun = false;
            btn_Start.Text = "开始测试";
            tbProSN.Text = "";
        }

        private void FillTestValue(object obj, EventArgs e)
        {
            clsInsertRow aInsertRow = obj as clsInsertRow;
            this.dgvTest.Rows[aInsertRow.iRow].Cells[clsTestItem.chn_Value].Value = aInsertRow.sValue;//测试值
            MoveToRow(aInsertRow.dgv, aInsertRow.iRow - 10, aInsertRow.iRow);

            if (aInsertRow.sResult == GDefine.ContentPass)
            {
                this.dgvTest.Rows[aInsertRow.iRow].Cells[clsTestItem.chn_Value].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
                this.dgvTest.Rows[aInsertRow.iRow].Cells[clsTestItem.chn_Result].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexPass);
            }
            else if (aInsertRow.sResult == GDefine.ContentFail)
            {
                this.dgvTest.Rows[aInsertRow.iRow].Cells[clsTestItem.chn_Value].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
                this.dgvTest.Rows[aInsertRow.iRow].Cells[clsTestItem.chn_Result].Style.BackColor = ColorTranslator.FromHtml(GDefine.ColorHexFail);
            }
            else
            {
            }
            this.dgvTest.Rows[aInsertRow.iRow].Cells[clsTestItem.chn_Result].Value = aInsertRow.sResult;//测试结果

            if (!m_dicResult.ContainsKey(aInsertRow.iRow))
            {
                JcELECDataResults result = new JcELECDataResults();
                result.fValue = Convert.ToSingle(aInsertRow.sValue);
                result.sPass = aInsertRow.sResult;
                m_dicResult.Add(aInsertRow.iRow, result);
            }
            else
            {
                m_dicResult[aInsertRow.iRow].fValue = Convert.ToSingle(aInsertRow.sValue);
                m_dicResult[aInsertRow.iRow].sPass = aInsertRow.sResult;
            }
        }

        private void SetDgvDataSource()
        {
            //清空测试值
            m_dtShow = m_dtTestItem.DefaultView.ToTable(false, m_arrShowList);
            dgvTest.DataSource = null;
            dgvTest.DataSource = m_dtShow;
            dgvTest.Columns[clsTestItem.chn_TestNo].Visible = false;
            dgvTest.Columns[clsTestItem.chn_LastValue].Visible = false;
            dgvTest.Columns[clsTestItem.chn_LastResult].Visible = false;

            dgvTest.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvTest.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            for (int i = 0; i < this.dgvTest.Columns.Count; i++)
            {
                this.dgvTest.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {
                if (m_dtTestItem.Rows[i][clsTestItem.chn_PortType].ToString().Trim() == "S11")
                {
                    m_dtShow.Rows[i][clsTestItem.chn_PortB_RCU] = "/";
                }
                else if (m_dtTestItem.Rows[i][clsTestItem.chn_PortType].ToString().Trim() == "S22")
                {
                    m_dtShow.Rows[i][clsTestItem.chn_PortA_RCU] = "/";
                }
            }

            dgvTest.CurrentCell = null;
            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {
                dgvTest.Rows[i].Visible = m_enableConfig[i];
                if (m_enableConfig[i])
                    dgvTest.CurrentCell = dgvTest.Rows[i].Cells[0];
            }
        }

        #region 获取配置

        private void BtnInstr_Click(object sender, EventArgs e)
        {
            TryConnectDlg(ref m_CInstrVNA, ref m_CLoadSwitch);
        }

        private void 仪表配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TryConnectDlg(ref m_CInstrVNA, ref m_CLoadSwitch);
        }

        private void 电性能配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!m_usrObj.HavePower(clsPowerManage.POWER_FEAFTURES.ELEC_CONFIG))
            {
                MessageBox.Show("权限不足！");
                return;
            }

            if (m_isLocalConfg)
            {
                FrmSConfigNewAntenna frmSConfg = new FrmSConfigNewAntenna(m_cTestConfigBuilder);
                frmSConfg.ShowDialog();
            }
            else
            {
                FrmConfigAntenna frmSConfg = new FrmConfigAntenna(FrmConfigAntenna.TYPE_SPARAM);
                frmSConfg.ShowDialog();
                initDataConfig();
            }
        }

        #region 加载配置
        private void initDataBaseNames()
        {//初始化数据库
            m_cTestConfigBuilder = new ClsDataSParamBuilder(GDefine.DBNameELEC);
            m_resultBuilder = new ClsDataResultForAntennaBuilder(GDefine.DBNameELEC);
            m_dicResult = new Dictionary<int, JcELECDataResults>();
        }

        private void initDataConfig()
        {
            cbProCode.Items.Clear();
            if (m_dtTestItem != null)
                m_dtTestItem.Clear();

            if (m_isLocalConfg)
            {//获取本地配置
                OpenFileDialog frmFile = new OpenFileDialog();
                frmFile.Multiselect = false;
                frmFile.InitialDirectory = Application.StartupPath + "\\config";
                frmFile.Filter = GDefine.FILTER_STRING_SPARAM;
                if (frmFile.ShowDialog() == DialogResult.OK)
                {//选择本地文件
                    cbProCode.Items.Add(frmFile.FileName);
                    cbProCode.SelectedIndex = 0;
                }
                else
                {
                    return;
                }
            }
            else
            {//获取服务器配置
                List<ProcodeNode> nodes = m_cTestConfigBuilder.getNodeList();
                if (nodes != null)
                {
                    foreach (var node in nodes)
                    {
                        cbProCode.Items.Add(node.Procode);
                    }
                }
            }

        }

        private void cbProCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sProCode = cbProCode.Text;

            if (!m_isLocalConfg)
            {//数据库数据
                m_cTestConfigBuilder.constructByProcode(sProCode);
                if (m_cTestConfigBuilder.construct(sProCode, "1.0"))
                {//下载配置
                    m_dtTestItem = m_cTestConfigBuilder.download(out m_testConfig);
                }
                else
                {
                    MessageBox.Show("未发现配置：" + sProCode);
                    return;
                }
            }
            else
            {//加载本地配置
                m_dtTestItem = m_cTestConfigBuilder.download(cbProCode.Text, out m_testConfig);
            }

            if (m_dtTestItem == null)
            {
                MessageBox.Show("配置文档错误!");
                return;
            }
            m_AntennaType = (AntennaType)m_testConfig[0].sAntennaType;
            cbRebootStatus.SelectedIndex = m_testConfig[0].sRetSpeed;
            if (m_testConfig[0].sCheckResult)
            {
                textcheck.Text = "检测";
            }
            else if (!m_testConfig[0].sCheckResult)
            {
                textcheck.Text = "不检测";
            }
            else
            {
                textcheck.Text = "错误";
            }

            m_enableConfig = new List<bool>();
            for (int i = 0; i < m_testConfig.Count; i++)
            {//初始化enable表
                m_enableConfig.Add(true);
            }

            m_dtTestItem.Columns.Add(clsTestItem.chn_Value);
            m_dtTestItem.Columns.Add(clsTestItem.chn_Result);
            m_dtTestItem.Columns.Add(clsTestItem.chn_LastValue);
            m_dtTestItem.Columns.Add(clsTestItem.chn_LastResult);
            m_dtTestItem.Columns.Add(clsTestItem.chn_NowValue);

            if (m_dtTestItem.Rows[0][clsTestItem.chn_RCUFlag].ToString().Trim() == "0")
            {//根据配置设置是否使用RCU
                m_Instr.RCU_Type = 0;
                m_Instr.RCU_Check = 0;
            }
            else if (m_dtTestItem.Rows[0][clsTestItem.chn_RCUFlag].ToString().Trim() == "1")
            {
                m_Instr.RCU_Type = 1;
                m_Instr.RCU_Check = 1;
            }
            else
            {
                m_Instr.RCU_Type = 1;
                m_Instr.RCU_Check = 0;
            }

            //重置特采功能
            //m_usrObj.aSpecial.bEnable = false;

            #region 展示测试界面需要显示的信息
            SetDgvDataSource();
            #endregion

            #region 初始化项目类
            m_cProject = new clsProject();
            m_cProject.ProjectId = "TEST";
            m_cProject.projectName = "";
            m_cProject.sNewTestMode = "1";
            m_cProject.iCodeLen = 3;

            m_TestTimes = -1;
            m_ChangeTimes = -1;
            List<string> lstOffsetBand = new List<string>();
            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {//生成需要校准的频段
                if (lstOffsetBand.IndexOf(m_dtTestItem.Rows[i][clsTestItem.chn_Band].ToString()) == -1)
                {
                    lstOffsetBand.Add(m_dtTestItem.Rows[i][clsTestItem.chn_Band].ToString());
                    m_cProject.Band += m_dtTestItem.Rows[i][clsTestItem.chn_Band].ToString() + ";";
                }

                int testTimes = Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_TestNo].ToString());
                if (testTimes > m_TestTimes)
                {
                    m_TestTimes = testTimes;
                }

                int testIndex = Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_Index].ToString());
                if (testIndex > m_ChangeTimes)
                {
                    m_ChangeTimes = testIndex;
                }
            }
            #endregion
        }
        #endregion

        #endregion

        #region 校准
        void setCalENA()
        {
            #region 统一设置
            string[] PortType = new string[4] { "S11", "S22", "S21", "S12" };
            string[] FormatType = new string[4] { "DISP_SWR", "DISP_SWR", "DISP_LOGM", "DISP_PHAS" };
            if (!m_CInstrVNA.SetTraceCoun(4))
            {
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            }
            for (int k = 0; k < 4; k++)
            {
                //trace 1 - k 操作
                if (!m_CInstrVNA.SetMeasType(k + 1, PortType[k]))
                {//S21
                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                }
                if (!m_CInstrVNA.SetDisplayFormat(k + 1, FormatType[k]))
                {//format//并且选中当前的trace
                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                }
            }
            ////下面是mark取点法------------------------------------------------------
            //if (!m_CInstrVNA.SetMark("MKR_MAX", 0, 1))
            //{
            //    tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
            //}
            //if (!m_CInstrVNA.SetMark("MKR_MIN", 0, 2))
            //{
            //    tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
            //}
            //if (!m_CInstrVNA.GetMarkYValue(out InsLo, 1))
            //{
            //    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            //}
            //if (!m_CInstrVNA.GetMarkYValue(out InsHi, 2))
            //{
            //    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            //}
            //-----------------------------------------------------------------------------*/            
            #endregion
        }
        void getCalENA(ref float s11, ref float s22, ref float s21)
        {
            float[] markMax = new float[4];
            #region 统一trig
            if (!m_CInstrVNA.BeforeTrig())
            {
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            }
            if (!m_CInstrVNA.TrigSingle())
            {
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            }
            if (!m_CInstrVNA.DisplayAutoScaleAll())
            {
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            }
            #endregion
            for (int k = 0; k < 4; k++)
            {
                if (k == 3) break;

                if (!m_CInstrVNA.TraceSel(k + 1))
                {//选中trace
                    tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
                }

                if (!m_CInstrVNA.SetMark("MKR_MAX", 0, 1))
                {
                    tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
                }

                if (!m_CInstrVNA.GetMarkYValue(out markMax[k], 1))
                {
                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                }
            }
            s11 = (float)Math.Abs(Math.Round(markMax[0], 2));
            s22 = (float)Math.Abs(Math.Round(markMax[1], 2));
            s21 = (float)Math.Abs(Math.Round(markMax[2], 2));
        }
        void creatCheckRecord(bool isCreat = true)
        {
            if (isCreat)
            {
                m_CheckRecord = new ClsCalRecord();
                m_lstCheckRecordItem = new List<ClsCalRecordItem>();
                m_CheckRecord.InstrumentID = m_CInstrVNA.GetIDN();
                m_CheckRecord.PCIP = m_usrObj.sEquID;
                m_CheckRecord.UserID = m_usrObj.sUser;
                m_CheckRecord.UserID2 = m_usrObj.sUser2;
                m_CheckRecord.ValueType = "电性能";
            }
            else
            {
                updateCalRecord();
                m_CheckRecord = null;
                m_lstCheckRecordItem = null;
            }
        }
        void updateCalRecord()
        {
            ClsDataCalResult CheckResult = new ClsDataCalResult(GDefine.DBNameELEC);
            if (CheckResult.updateRecord(m_CheckRecord, m_lstCheckRecordItem))
            {
                tb_Test.AppendText("上传校准数据成功" + "\r\n");
                MessageBox.Show("上传校准数据成功");
            }
            else
            {
                tb_Test.AppendText("上传校准数据失败" + "\r\n");
                MessageBox.Show("上传校准数据失败");
            }
        }
        void twoPortCal(bool IsManual = true)
        {
            if (m_IsRun)
            {
                return;
            }

            if (!ConnectionTest())
            {//如果连接失败弹出连接配置框
                return;
            }

            float f1 = 0, f2 = 0;
            if (m_dtTestItem == null)
            {
                MessageBox.Show("请先加载配置!");
                return;
            }
            if (m_cProject.Band == null || m_cProject.Band == "")
            {
                tb_Test.AppendText("请对方案中的校准频段赋值!");
                return;
            }

            creatCheckRecord(true);
            string[] strBandArry = m_cProject.Band.Split(';');
            for (int i = 0; i < strBandArry.Length; i++)
            {
                if (strBandArry[i] == "") continue;
                if (!GetFreqRange(strBandArry[i], ref f1, ref f2))
                {
                    tb_Test.AppendText("方案中的校准频段格式不符3,参考: 0-8500;1735-1785;1830-1880; ");
                    return;
                }
                if (MessageBox.Show("开始双端口校准,频段：" + strBandArry[i] + "请准备！", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    tb_Test.AppendText("开始双端口校准...\r\n");
                    IsManualOffset = IsManual;
                    if (!IsManual)
                        MessageBox.Show("请连接 Port" + 1 + " <---> Port" + 2 + " !\r\n");

                    TraceECal(f1, f2, 0, 201, 1, 2);

                    setCalENA();
                    MessageBox.Show("请使用THRU(直通)件对接端口" + 1 + "，端口" + 2 + "" + ",以检测校准是否成功");
                    FrmCalConfirm frmCalConf = new FrmCalConfirm("1-2", strBandArry[i]);
                    frmCalConf.evtgetCalENA += new FrmCalConfirm.delgetCalENA(getCalENA);
                    frmCalConf.ShowDialog();
                    if (frmCalConf.DialogResult == DialogResult.OK)
                    {
                        m_lstCheckRecordItem.Add(frmCalConf.RdItem1);
                        m_lstCheckRecordItem.Add(frmCalConf.RdItem2);
                        m_lstCheckRecordItem.Add(frmCalConf.RdItem3);
                    }
                    else if (frmCalConf.DialogResult == DialogResult.Retry)
                    {
                        i--;
                        frmCalConf.Dispose();
                        continue;
                    }
                    else
                    {

                    }
                    frmCalConf.Dispose();


                    string sCalReg = "N2" + "-" + m_cProject.ProjectId + "-" + strBandArry[i] + "-PORT" + "1-2";
                    if (!m_CInstrVNA.SaveToReg(sCalReg))
                    {
                        tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
                        MessageBox.Show("校准错误：" + m_CInstrVNA.m_sbErr.ToString());
                        return;
                    }
                    else
                    {
                        tb_Test.AppendText("生成校准文件:" + sCalReg + "\r\n");
                    }
                }
                else
                    return;
            }
            creatCheckRecord(false);
        }
        private void 双端口校准ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (m_IsRun)
            //{
            //    return;
            //}

            //if (!ConnectionTest())
            //{//如果连接失败弹出连接配置框
            //    return;
            //}

            //float f1 = 0, f2 = 0;
            //if (m_dtTestItem == null)
            //{
            //    MessageBox.Show("请先加载配置!");
            //    return;
            //}
            //if (m_cProject.Band == null || m_cProject.Band == "")
            //{
            //    tb_Test.AppendText("请对方案中的校准频段赋值!");
            //    return;
            //}

            //creatCheckRecord(true);
            //string[] strBandArry = m_cProject.Band.Split(';');
            //for (int i = 0; i < strBandArry.Length; i++)
            //{
            //    if (strBandArry[i] == "") continue;
            //    if (!GetFreqRange(strBandArry[i], ref f1, ref f2))
            //    {
            //        tb_Test.AppendText("方案中的校准频段格式不符3,参考: 0-8500;1735-1785;1830-1880; ");
            //        return;
            //    }
            //    if (MessageBox.Show("开始双端口校准,频段：" + strBandArry[i] + "请准备！", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
            //    {
            //        tb_Test.AppendText("开始双端口校准...\r\n");
            //        IsManualOffset = true;

            //        TraceECal(f1, f2, 0, 201, 1, 2);

            //        setCalENA();
            //        MessageBox.Show("请使用THRU(直通)件对接端口" + 1 + "，端口" + 2 + "" + ",以检测校准是否成功");
            //        FrmCalConfirm frmCalConf = new FrmCalConfirm("1-2", strBandArry[i]);
            //        frmCalConf.evtgetCalENA += new FrmCalConfirm.delgetCalENA(getCalENA);                   
            //        frmCalConf.ShowDialog();
            //        if (frmCalConf.DialogResult == DialogResult.OK)
            //        {
            //            m_lstCheckRecordItem.Add(frmCalConf.RdItem1);
            //            m_lstCheckRecordItem.Add(frmCalConf.RdItem2);
            //            m_lstCheckRecordItem.Add(frmCalConf.RdItem3);
            //        }
            //        else if (frmCalConf.DialogResult == DialogResult.Retry)
            //        {
            //            i--;
            //            frmCalConf.Dispose();
            //            continue;
            //        }
            //        else
            //        {

            //        }
            //        frmCalConf.Dispose();


            //        string sCalReg = "N2" + "-" + m_cProject.ProjectId + "-" + strBandArry[i] + "-PORT" + "1-2";
            //        if (!m_CInstrVNA.SaveToReg(sCalReg))
            //        {
            //            tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
            //            MessageBox.Show("校准错误：" + m_CInstrVNA.m_sbErr.ToString());
            //            return;
            //        }
            //        else
            //        {
            //            tb_Test.AppendText("生成校准文件:" + sCalReg + "\r\n");
            //        }
            //    }
            //}

            //creatCheckRecord(false);


            ////if (MessageBox.Show("开始双端口校准, 请准备！", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
            ////{
            ////    tb_Test.AppendText("开始双端口校准...\r\n");
            ////    IsManualOffset = true;
            ////    float f1 = 0.3f * 1000 * 1000; //MHZ
            ////    float f2 = 3000f * 1000 * 1000;

            ////    TraceECal(f1, f2, 10, 201, 1, 2);

            ////    //string sCalReg = "N2-ALL-0.3-3000";

            ////    if (!m_CInstrVNA.SaveToReg(CALREG_ALL_BAND))
            ////    {
            ////        tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
            ////        MessageBox.Show("生成校准文件错误：" + m_CInstrVNA.m_sbErr.ToString());
            ////    }
            ////    else
            ////    {
            ////        tb_Test.AppendText("生成校准文件:" + CALREG_ALL_BAND + "\r\n");
            ////    }
            ////}
        }

        private void 机械校准ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            twoPortCal(true);
        }

        private void 电子校准ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            twoPortCal(false);
        }

        private void 手动校准ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_dtTestItem == null)
            {
                MessageBox.Show("请先加载配置!");
                return;
            }

            if (m_Instr.Switch_Type == (int)SwitchType.SWITCH_NONE)
            {
                MessageBox.Show("您未选择开关箱，只能采用双端口校准!");
                return;
            }
            else
            {
                IsManualOffset = true;
                // DoMultiPortCal(m_PortCount);
                DoMultiPortCal(m_Instr.Switch_Count + 1);
            }
        }

        private void 开始校准ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_dtTestItem == null)
            {
                MessageBox.Show("请先加载配置!");
                return;
            }

            if (m_Instr.Switch_Type == (int)SwitchType.SWITCH_NONE)
            {
                MessageBox.Show("您未选择开关箱，只能采用双端口校准!");
                return;
            }
            else
            {
                IsManualOffset = false;
                //   DoMultiPortCal(m_PortCount);
                DoMultiPortCal(m_Instr.Switch_Count + 1);
            }
        }

        private void DoMultiPortCal(int iPortCount)
        {
            if (!m_IsRun)
            {
                if (!ConnectionTest())
                {//如果连接失败弹出连接配置框
                    return;
                }

                creatCheckRecord(true);

                //可以通过遍历所有的测试项得知那些链路需要校准，给予建议
                string[] arrSugest = new string[1024];
                string sSugest = "建议校准项: ", sTestFlag, sPortA, sPortB, sPortANum, sPortBNum, sLastSugest = "", sCurSugest = "";
                int iTestCount = 0, iSugestNum = 0;
                for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
                {
                    sPortA = m_dtTestItem.Rows[i][ClsDataSParam.chn_PortA].ToString().Trim();
                    sPortB = m_dtTestItem.Rows[i][ClsDataSParam.chn_PortB].ToString().Trim();
                    //跳过免测项
                    sTestFlag = m_dtTestItem.Rows[i][ClsDataSParam.chn_Done].ToString().Trim();
                    if (sTestFlag != "True") continue;

                    iTestCount = Convert.ToInt32(m_dtTestItem.Rows[i][ClsDataSParam.chn_TestNo].ToString().Trim());
                    sPortANum = GetStrPortAB(iTestCount, sPortA);
                    sPortBNum = GetStrPortAB(iTestCount, sPortB);
                    if (sPortANum == sPortBNum) continue;
                    if (sPortANum == null || sPortBNum == null)
                    {//仅提醒就可以了
                        MessageBox.Show("测试项 " + (i + 1) + " 无法找到对应的端口 " + sPortA + "," + sPortB + " 请检查开关箱路径表");
                        sSugest = "";
                        break;
                    }
                    sCurSugest = sPortANum + "-" + sPortBNum + "; ";
                    if (sLastSugest != sCurSugest)
                    {
                        sLastSugest = sCurSugest;

                        if (ExistInList(arrSugest, sCurSugest) == -1)
                        {
                            arrSugest[iSugestNum] = sCurSugest;
                            sSugest += sCurSugest;
                            iSugestNum++;
                        }
                    }
                }

                int iPortMaxCount = iPortCount;
                tb_Test.AppendText("ECAL  Start!\r\n");
                for (int i = 1; i <= iPortMaxCount; i++)
                {
                    for (int j = 1; j <= iPortMaxCount; j++) //int j = i + 1;
                    {
                        sCurSugest = i + "-" + j + "; ";
                        if (ExistInList(arrSugest, sCurSugest) == -1)
                        {
                            continue;
                        }

                        tb_Test.AppendText("ECAL: " + i.ToString() + j.ToString() + "\r\n");
                        string strTitle = "请连接 Port" + i.ToString() + " <---> Port" + j.ToString() + " !\r\n";//+"(300K, 3G)";
                        int iExit = NewECal(iPortCount, strTitle, i, j, 0, 0, sSugest);
                        if (iExit == -1)
                            return;
                        else if (iExit == 0)
                            continue;
                    }
                }
                tb_Test.AppendText("ECAL  End!\r\n");
                MessageBox.Show("校准完成!");

                creatCheckRecord(false);
            }
        }

        private int NewECal(int iPortCount, string s, int p1, int p2, float CalF1, float CalF2, string sSugest)
        {//六端口 或 12 端口 中的其中一次校准        //"N12-2227-1950-5240-PORT1-3";
            //"N06-2227-1980-5250-PORT2-4";
            //"N06-2227-0-8500-PORT2-4";
            CalibrationForm frmCal = new CalibrationForm(s, sSugest);
            DialogResult dr = frmCal.ShowDialog();
            if (dr == DialogResult.Ignore)
            {
                tb_Test.AppendText("跳过!\r\n");
                return 0;
            }
            else if (dr != DialogResult.OK)
            {
                tb_Test.AppendText("退出!\r\n");
                return -1;
            }
            int iPower = Convert.ToInt32(MakeNoSufix(frmCal.m_sPower));
            int iPoints = Convert.ToInt32(frmCal.m_sPoints);
            if (IsSwitch)
            {//切换开关
                if (!m_CLoadSwitch.Select_Switch_port(p1, p2, 500))
                {
                    tb_Test.AppendText(m_CLoadSwitch.m_sbErr.ToString());
                }
            }

            if (IsVNA)
            {//开始校准
                float f1 = 0, f2 = 0;
                if (m_cProject.Band == null || m_cProject.Band == "")
                {
                    tb_Test.AppendText("请对方案中的校准频段赋值!");
                    return -1;
                }
                string[] strBandArry = m_cProject.Band.Split(';');
                for (int i = 0; i < strBandArry.Length; i++)
                {
                    if (strBandArry[i] == "") continue;

                    if (!GetFreqRange(strBandArry[i], ref f1, ref f2))
                    {
                        tb_Test.AppendText("方案中的校准频段格式不符3,参考: 0-8500;1735-1785;1830-1880; ");
                        return 0;
                    }

                    if (f1 == 0)
                    {//segment校准
                        //SegmECal(f1, f2);
                    }
                    else
                    {//trace校准
                        TraceECal(f1, f2, iPower, iPoints, p1, p2);


                        setCalENA();
                        MessageBox.Show("请使用THRU(直通)件对接端口" + p1 + "，端口" + p2 + "" + ",以检测校准是否成功");
                        FrmCalConfirm frmCalConf = new FrmCalConfirm(p1 + "-" + p2, strBandArry[i]);
                        frmCalConf.evtgetCalENA += new FrmCalConfirm.delgetCalENA(getCalENA);
                        frmCalConf.ShowDialog();
                        if (frmCalConf.DialogResult == DialogResult.OK)
                        {
                            m_lstCheckRecordItem.Add(frmCalConf.RdItem1);
                            m_lstCheckRecordItem.Add(frmCalConf.RdItem2);
                            m_lstCheckRecordItem.Add(frmCalConf.RdItem3);
                        }
                        else if (frmCalConf.DialogResult == DialogResult.Retry)
                        {
                            frmCalConf.Dispose();
                            NewECal(iPortCount, s, p1, p2, CalF1, CalF2, sSugest);
                        }
                        else
                        {

                        }
                        frmCalConf.Dispose();



                    }

                    string sCalReg = "N" + iPortCount + "-" +
                        m_cProject.ProjectId + "-" + strBandArry[i] + "-PORT" + p1.ToString() + "-" + p2.ToString();

                    if (!m_CInstrVNA.SaveToReg(sCalReg))
                    {
                        tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
                        MessageBox.Show("校准错误：" + m_CInstrVNA.m_sbErr.ToString());
                        return -1;
                    }
                    else
                    {
                        tb_Test.AppendText("生成校准文件:" + sCalReg + "\r\n");
                    }
                }
            }
            return 1;
        }

        private void TraceECal(float f1, float f2, int power, int iPoints, int p1, int p2)
        {//trace 校准
            if (!m_CInstrVNA.ResetInstr())
            {
                tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
            }
            if (!m_CInstrVNA.SetSweepType("LIN"))
            {
                tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
            }
            //setCalENA();
            //设置频率
            if (!m_CInstrVNA.SetFrequency(f1, f2))
            {
                tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
            }

            if (!m_CInstrVNA.SetSweepPoints(iPoints))
            {
                tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
            }

            if (!m_CInstrVNA.SetIFBandWidth(3000))//3000
            {
                tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
            }
            if (f1 >= 3000000000)
            {
                if (!m_CInstrVNA.SetPower(0))
                {//对于3G以上的频段，例如3000-8500, power不能设置到10，默认设为0
                    tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
                }
            }
            else
            {
                if (!m_CInstrVNA.SetPower(power))
                {
                    tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
                }
            }

            if (!IsManualOffset)
            {//电子校准
                if (!m_CInstrVNA.SetECalKit())
                {//cal
                    tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
                }
            }
            else
            {//手动校准
                if (!ManualCal(p1, p2))
                {//cal
                    tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
                }
            }
        }

        private bool ManualCal(int p1, int p2)
        {
            m_CInstrVNA.SetCalFor2Port();
            MessageBox.Show("端口" + p1 + "，请接 OPEN (开路)校准件");
            m_CInstrVNA.SetCalFor2Open1();
            MessageBox.Show("端口" + p1 + "，请接 SHORT (短路)校准件");
            m_CInstrVNA.SetCalFor2Shor1();
            MessageBox.Show("端口" + p1 + "，请接 LOAD (负载)校准件");
            m_CInstrVNA.SetCalFor2Load1();

            MessageBox.Show("端口" + p2 + "，请接 OPEN (开路)校准件");
            m_CInstrVNA.SetCalFor2Open2();
            MessageBox.Show("端口" + p2 + "，请接 SHORT (短路)校准件");
            m_CInstrVNA.SetCalFor2Shor2();
            MessageBox.Show("端口" + p2 + "，请接 LOAD (负载)校准件");
            m_CInstrVNA.SetCalFor2Load2();

            MessageBox.Show("请使用THRU(直通)件对接端口" + p1 + "，端口" + p2 + "");
            m_CInstrVNA.SetCalFor2Thru1();
            m_CInstrVNA.SetCalFor2Thru2();
            //m_CInstrVNA.SetCalFor2Isol1();
            //m_CInstrVNA.SetCalFor2Isol2();
            m_CInstrVNA.SetCalFor2Save();

            return true;
        }

        private string GetStrPortAB(int iSwitchIndex, string str)
        {
            return str;
            //int iPortNum = 0;
            //if (m_Instr.Switch_Type == (int)SwitchType.SWITCH_SW)
            //{
            //    iPortNum = 6;
            //}
            //else if (m_Instr.Switch_Type == (int)SwitchType.SWITCH_JC ||
            //    m_Instr.Switch_Type == (int)SwitchType.SWITCH_JieXi)
            //{
            //    iPortNum = 12;
            //}
            //else
            //{
            //    return null;
            //}
            //if (m_dtSwitchLoad.Rows.Count == 0)
            //{
            //    return null;
            //}
            //for (int i = 0; i < iPortNum; i++)
            //{
            //    if (str == m_dtSwitchLoad.Rows[iSwitchIndex - 1][i].ToString())
            //    {
            //        return (i + 1).ToString();
            //    }
            //}
        }

        private string MakeNoSufix(string sOriginal)
        {
            Regex rx = new Regex(@"(\d+)\.(\d+)|(\d+)");
            MatchCollection ms = rx.Matches(sOriginal);
            if (ms.Count > 0)
            {
                return ms[0].Value.ToString();
            }
            else
                return "";
        }

        #endregion

        #region 连接

        private bool TryConnectDlg(ref clsBaseVNA m_CInstrVNA, ref InstrSwitch m_CLoadSwitch)
        {//仪表连接等配置界面
            ConnectInstr InstrDlg = new ConnectInstr(m_Instr, m_CInstrVNA, m_CLoadSwitch);
            if (InstrDlg.ShowDialog() == DialogResult.OK)
            {
                m_CInstrVNA = InstrDlg.m_curVNA;
                m_CLoadSwitch = InstrDlg.m_curSwitch;
                ShowInfo();
                return true;
            }
            else
            {
                return false;
            }
        }

        protected void ShowInfo()
        {
            //this.VNA_X_Type = m_Instr.VNA_X_Type;
            //lbl_VNA_X_Type.Text = "测试方式: " + VNA_X_Type.ToString();
            lbl_VNA.Text = "仪表类型: " + m_Instr.VNAName;

            if (m_Instr.Switch_Type == (int)SwitchType.SWITCH_JC)
            {
                lbl_Switch.Text = "矩阵开关: 研辰   通信端口: " + m_Instr.Switch_ConnPort;
                m_PortCount = 8;
                //m_TestTimes = 1;
            }
            else if (m_Instr.Switch_Type == (int)SwitchType.SWITCH_JieXi)
            {
                lbl_Switch.Text = "矩阵开关: Jiexi   通信端口: " + m_Instr.Switch_ConnPort;
                m_PortCount = 12;
                //m_TestTimes = 1;
            }
            else if (m_Instr.Switch_Type == (int)SwitchType.SWITCH_SW)
            {
                lbl_Switch.Text = "矩阵开关: SunWare   通信端口: " + m_Instr.Switch_ConnPort;
                m_PortCount = 6;
                //m_TestTimes = 2;
            }
            else
            {
                lbl_Switch.Text = "矩阵开关：未使用";
                m_PortCount = 12;
                //m_TestTimes = 2;
            }
        }

        protected bool ConnectionTest()
        {//测试前先检查现有连接， 
            ConnectCtrl aConnectCtrl = new ConnectCtrl();
            if (!aConnectCtrl.TryInstr(m_Instr, ref m_CInstrVNA))
            {
                MessageBox.Show("连接仪表失败!");
                return TryConnectDlg(ref m_CInstrVNA, ref m_CLoadSwitch);
            }

            if (!aConnectCtrl.TrySwitch(m_Instr, ref m_CLoadSwitch))
            {
                MessageBox.Show("连接开关箱失败!");
                return TryConnectDlg(ref m_CInstrVNA, ref m_CLoadSwitch);
            }

            return true;
        }

        #endregion

        #region RCU控制

        private bool ConnectionRCU()
        {
            bool ret = false;

            try
            {
                #region 连接RCU

                if (m_rcuObj == null)
                {
                    m_rcuObj = new RCUrunner(m_Instr.RCU_Addr);
                }

                if (!DEBUG_TEST && m_Instr.RCU_Type != 0)
                {
                    if (!m_rcuObj.connect(""))
                    {
                        MessageBox.Show("RCU设备连接失败!");
                        return false;
                    }

                    if ((m_dicRCUs = getListRCU()) == null)
                    {//初始化RCU列表
                        return false;
                    }

                    if (m_dicRCUs.Count == 0)
                    {
                        return false;
                    }
                }
                else
                {
                    #region ---------------(debug_test)-------------------
                    m_dicRCUs = new Dictionary<string, RCUInfo>();
                    for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
                    {
                        string sRCUName = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                        string nowRCUindex = sRCUName.Substring(0, sRCUName.Length - GDefine.RCU_PORT_NAME.Length);
                        if (!m_dicRCUs.ContainsKey(nowRCUindex))
                        {
                            RCUInfo info = new RCUInfo();
                            info.RCUIndex = nowRCUindex;
                            info.SN = "DEBUG";
                            info.angle = -1;

                            info.unit = new RCUUnit();
                            info.unit.hardware_v = "debug";
                            info.unit.firmvare_v = "debug";
                            info.unit.aisg_v = "debug";
                            info.unit.build_date = "debug";
                            info.unit.unit_sum = 0;
                            info.unit.unit = 0;
                            info.unit.module_num = "debug";
                            info.unit.module_sn = "debug";
                            info.unit.angle_current = 0;

                            m_dicRCUs.Add(info.RCUIndex, info);
                        }
                    }
                    #endregion
                }

                string sLog = "";
                foreach (var obj in m_dicRCUs)
                {
                    sLog += obj.Key + ", ";
                    sLog += obj.Value.SN + ", ";
                    sLog += obj.Value.angle.ToString() + "\r\n";
                }

                #endregion

                if (m_Instr.RCU_Type != 0 && m_Instr.RCU_Check == 1)
                {
                    #region 检测序列号
                    for (int i = 0; i < 1; i++)
                    {
                        bool bCheck = false;
                        this.Invoke(new ThreadStart(delegate
                        {
                            FrmCheckSN frmCheck = new FrmCheckSN();
                            if (frmCheck.ShowDialog() == DialogResult.OK)
                            {
                                foreach (var rcu in m_dicRCUs)
                                {
                                    if (frmCheck.textProductID.Text.Contains(rcu.Value.SN))
                                    {
                                        bCheck = true;
                                        //break;
                                    }
                                    //else
                                    //{//识别模块二维码--MT固定公司标识
                                    //    string checksn = frmCheck.textProductID.Text.Trim();
                                    //    if (checksn.Length < 3) break;
                                    //    string sn = rcu.Value.SN.Substring(0, checksn.Length - 2);
                                    //    if (checksn.Contains(sn))
                                    //    {
                                    //        bCheck = true;
                                    //    }
                                    //}
                                }
                            }
                        }));

                        if (!bCheck)
                        {
                            if (MessageBox.Show("序列号检查错误！是否重试？", "条码检测", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                i--;
                                continue;
                            }
                            m_SNcheckPass = bCheck;
                            return false;
                        }
                        else
                        {
                            m_SNcheckPass = bCheck;
                            break;
                        }
                    }
                    #endregion
                }

                #region 进入初始状态

                FrmTips ctl_frm_message = new FrmTips("初始化RCU....");
                this.BeginInvoke(new ThreadStart(delegate
                {
                    tb_Test.AppendText(sLog);
                    ctl_frm_message.Show();
                    tb_Test.AppendText("正在初始化RCU...\r\n");
                }));

                ret = initRCUAngle();

                this.Invoke(new ThreadStart(delegate
                {
                    if (!ret)
                        tb_Test.AppendText("初始化RCU失败.\r\n");
                    else
                        tb_Test.AppendText("初始化RCU成功.\r\n");

                    ctl_frm_message.Close();
                    ctl_frm_message = null;
                }));

                #endregion
            }
            catch (Exception ex)
            {
                this.Invoke(new ThreadStart(delegate { MessageBox.Show("RCU 初始化错误:\r\n" + ex.Message); }));
            }

            return ret;
        }

        private Dictionary<string, RCUInfo> getListRCU()
        {
            #region Get RCU List
            //尝试连接RCU，并获取LIST
            //string[] lstRcuSN = m_rcuObj.get_list();
            //if (lstRcuSN == null || lstRcuSN.Length == 0)
            //{
            //    MessageBox.Show("RCU List 失败： 请重新连接RCU线缆！");
            //    return null;
            //}
            //var dicRCUs = new Dictionary<string, RCUInfo>();
            //for (int i = 0; i < lstRcuSN.Length; i++)
            //{
            //    RCUInfo info = m_rcuObj.getRCUinfo(lstRcuSN[i]);
            //    if (info == null)
            //    {
            //        MessageBox.Show("RCU Info 失败： " + m_rcuObj.result);
            //        return null;
            //    }
            //    dicRCUs.Add(info.RCUIndex, info);
            //}
            #endregion

            var dicRCUs = m_rcuObj.getRCUInfoList(m_productObj.rcuConfig);
            if (dicRCUs == null)
            {
                this.BeginInvoke(new ThreadStart(delegate
                {
                    tb_Test.AppendText(m_rcuObj.cmd.Substring(0, m_rcuObj.cmd.Length));
                    tb_Test.AppendText(m_rcuObj.result);
                }));
            }

            return dicRCUs;
        }

        private bool setRCUIndex(string sRCUIndex, int iAngle)
        {//rcu设置
            string nowRCUindex = sRCUIndex;
            if (iAngle * 10 == m_dicRCUs[nowRCUindex].angle)
            {
                return true;
            }

            if (m_Instr.RCU_Type == 0)
            {//手动调度
                m_dicRCUs[nowRCUindex].angle = iAngle * 10;
                return true;
            }

            if (!DEBUG_TEST)
            {
                //开始调角度
                if (!m_rcuObj.setAngle(m_dicRCUs[nowRCUindex], iAngle * 10, m_iSpeed))
                {
                    this.BeginInvoke(new ThreadStart(delegate
                    {
                        tb_Test.AppendText("==>" + m_rcuObj.cmd.Substring(0, m_rcuObj.cmd.Length));
                        tb_Test.AppendText("==>" + m_rcuObj.result);
                    }));
                    return false;
                }

                this.BeginInvoke(new ThreadStart(delegate
                {
                    tb_Test.AppendText("RCU: set TestAngle=" + iAngle + " , speed = " + m_iSpeed + "\r\n");
                }));

                m_dicRCUs[nowRCUindex].angle = iAngle * 10;
            }
            else
            {
                #region ---------------(debug_test)-------------------

                //On_evt_log_handle("正在RCU调度: " + m_config.RCUIndex + ", " + angle.ToString(), new EventLoggingArgs(true, null));
                for (int i = 0; i < 20; i++)
                {
                    Thread.Sleep(500);
                }

                this.BeginInvoke(new ThreadStart(delegate
                {
                    tb_Test.AppendText("RCU: set TestAngle=" + iAngle + " , speed = \r\n");
                }));

                m_dicRCUs[nowRCUindex].angle = iAngle * 10;

                #endregion
            }

            return true;
        }

        private bool initRCUAngle()
        {
            if (m_RevertAngle == 0)
                m_isInitMaxAngle = true;
            else
                m_isInitMaxAngle = false;

            Dictionary<string, Point> dicAngle = new Dictionary<string, Point>();

            #region 初始化角度
            bool isOneAngle = false;
            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {//将RCU初始化为最大角度
                if (m_dtTestItem.Rows[i][clsTestItem.chn_TestFunction].ToString() == "Continue")
                {
                    if (m_dtTestItem.Rows[i][clsTestItem.chn_Done].ToString().Trim() != "True")
                    {
                        continue;
                    }

                    string sMaxAngle = "";
                    string sMinAngle = "";
                    Regex reg = new Regex(@"(\d+|-\d+)-(\d+|-\d+)");
                    var m = reg.Match(m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString());
                    if (m.Success && m.Groups.Count == 3)
                    {
                        sMaxAngle = m.Groups[2].Value;
                        sMinAngle = m.Groups[1].Value;
                    }
                    else
                    {
                        MessageBox.Show("配置文件中角度设置错误,请检查!");
                        return false;
                    }

                    ////获取最大角度
                    //string sMaxAngle = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString().Split('-')[1];
                    int iMaxAngle = Convert.ToInt32(sMaxAngle);

                    ////获取最小角度
                    //string sMinAngle = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString().Split('-')[0];
                    int iMinAngle = Convert.ToInt32(sMinAngle);

                    if (iMaxAngle == iMinAngle) isOneAngle = true;

                    //获取RCU端口序列
                    string sPortA_RCUIPort = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                    string sPortA_RCUIndex = sPortA_RCUIPort.Substring(0, sPortA_RCUIPort.Length - GDefine.RCU_PORT_NAME.Length);

                    if (!dicAngle.ContainsKey(sPortA_RCUIndex))
                    {//记录最大和最小角度
                        dicAngle.Add(sPortA_RCUIndex, new Point(iMinAngle, iMaxAngle));
                    }

                    int iNeedAngle = m_isInitMaxAngle ? iMaxAngle : iMinAngle;
                    if (m_dicRCUs[sPortA_RCUIndex].angle != iNeedAngle * 10)
                    {//先设置预设角度
                        for (int tryNum = 0; tryNum < 1; tryNum++)
                        {
                            if (!setRCUIndex(sPortA_RCUIndex, iNeedAngle))
                            {
                                if (MessageBox.Show("RCU调度失败，是否重试", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                                {//重新开始,降低速度
                                    tryNum--;
                                }
                                else
                                {
                                    return false;
                                }
                            }
                            Thread.Sleep(100);
                        }
                    }
                }
            }

            if (m_Instr.RCU_Type == 0 && !isOneAngle)
            {//手动调度提示
                string sTipsAngleMax = "";
                string sTipsAngleMin = "";
                foreach (var port in dicAngle)
                {//获取连线端口数
                    sTipsAngleMin += port.Key + " ==> " + port.Value.X + "\r\n";
                    sTipsAngleMax += port.Key + " ==> " + port.Value.Y + "\r\n";
                }
                if (m_isInitMaxAngle)
                {
                    MessageBox.Show("请将所接电缆的端口调度:\r\n" + sTipsAngleMax);
                }
                else
                {
                    MessageBox.Show("请将所接电缆的端口调度:\r\n" + sTipsAngleMin);
                }
            }

            #endregion

            #region 排列

            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {//排列，先测最大角度的带间隔离，其次测试驻波，最后测试最小小角度的带间隔离
                string sPortA_RCUIPort = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                string sPortA_RCUIndex = sPortA_RCUIPort.Substring(0, sPortA_RCUIPort.Length - GDefine.RCU_PORT_NAME.Length);

                string sPortB_RCUIPort = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                string sPortB_RCUIndex = sPortB_RCUIPort.Substring(0, sPortB_RCUIPort.Length - GDefine.RCU_PORT_NAME.Length);

                if (m_dtTestItem.Rows[i][clsTestItem.chn_TestFunction].ToString() == "Single")
                {//带间隔离测试
                    //if (dicAngle.ContainsKey(sPortA_RCUIndex))
                    //{
                    //    continue;
                    //}

                    int sPortA_Angle = Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString());
                    int sPortB_Angle = Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Angle].ToString());

                    if (sPortA_Angle != dicAngle[sPortA_RCUIndex].X && sPortB_Angle != dicAngle[sPortB_RCUIndex].X)
                    {//最大角度测试
                        string sTestNo = m_isInitMaxAngle ? "1" : "3";
                        m_dtTestItem.Rows[i][clsTestItem.chn_TestNo] = sTestNo;
                        m_dtShow.Rows[i][clsTestItem.chn_TestNo] = sTestNo;
                    }
                    else
                    {//最小角度测试
                        string sTestNo = m_isInitMaxAngle ? "3" : "1";
                        m_dtTestItem.Rows[i][clsTestItem.chn_TestNo] = sTestNo;
                        m_dtShow.Rows[i][clsTestItem.chn_TestNo] = sTestNo;
                    }
                }
                else
                {//驻波测试
                    m_dtTestItem.Rows[i][clsTestItem.chn_TestNo] = "2";
                    m_dtShow.Rows[i][clsTestItem.chn_TestNo] = "2";
                }
            }
            //设置测试次数
            m_TestTimes = 3;

            #endregion

            return true;
        }

        private bool initRCUAngleTD(int x, int y)
        {
            //   string agl = m_INTdicTestPortsTD[x].lstAngle[y];
            if (m_Instr.RCU_Type == 0)
            {//手动调度提示
                List<string> lstTips = new List<string>(); List<string> lstAgls = new List<string>();
                for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
                {
                    if (m_dtTestItem.Rows[i][clsTestItem.chn_Index].ToString() != x.ToString() || m_dtTestItem.Rows[i][clsTestItem.chn_TestNo].ToString() != y.ToString() || !m_productObj.enableConfig[i] || !m_productObj.enableTestItem[i])
                        continue;
                    string t1 = "", t2 = "", agl1 = "", agl2 = "";
                    t1 = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                    t2 = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString();
                    agl1 = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString();
                    agl2 = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Angle].ToString();
                    if (lstTips.IndexOf(t1) < 0) { lstTips.Add(t1); lstAgls.Add(agl1); }
                    if (lstTips.IndexOf(t2) < 0) { lstTips.Add(t2); lstAgls.Add(agl2); }
                }


                string sTipsAngle = "";
                // int I=0;
                foreach (var port in m_INTdicTestPortsTD[x].lstTestPort)
                {//获取连线端口数
                    //string rcu = port.Split('-')[0];
                    //string tip=lstTips[I++].Split('-')[0];
                    //if (tip==rcu)
                    //    sTipsAngle += tip + " ==> " + lstAgls[lstTips.IndexOf(port)] + "\r\n";
                    if (lstTips.IndexOf(port) > -1)
                        sTipsAngle += port + " ==> " + lstAgls[lstTips.IndexOf(port)] + "\r\n";
                }
                if (sTipsAngle.Length <= 0) return false;
                MessageBox.Show("请将所接电缆的端口调度:\r\n" + sTipsAngle);
            }
            return true;
        }

        private void continueSetRCUIndex(ImpCtrl ctl, string sRCUIndex, int iAngle)
        {
            //if (!GDefine.IS_RCU_DEBUG_TEST)
            //{
            //    ctl.bCtrl = setRCUIndex(sRCUIndex, iAngle);
            //}
            //else
            //{
            //    Thread.Sleep(5000);
            //    ctl.bCtrl = false;
            //}

            ctl.bCtrl = setRCUIndex(sRCUIndex, iAngle);

            if (m_Instr.RCU_Type == 0)
            {
                //this.BeginInvoke(new ThreadStart(delegate
                //{
                MessageBox.Show(sRCUIndex + " 手动调度 ==> " + iAngle + "\r\n" + "当完成调度后，点击确定！");
                //}));
            }

            ctl.bQuit = true;
        }

        private bool RCUProcessRebootStatue()
        {
            //if (iRebootStatus != 0 && iRebootStatus != 1)
            //{
            //    return true;
            //}
            if (m_Instr.RCU_Type == 0)
            {
                return true;
            }

            foreach (var dic in m_dicRCUs)
            {
                bool isrev = true;
                int source_angle = dic.Value.angle;
                int source_speed = 0;

                if (m_productObj.rcuConfig != null)
                {
                    source_speed = m_productObj.rcuConfig.unit[0].speed;
                }
                else
                {
                    source_speed = 0;
                }

                if (dic.Value.angle != -1)
                {
                    if (!GDefine.IS_RCU_DEBUG_TEST)
                    {
                        //FrmTips ctl_frm_message = new FrmTips("正在RCU调度: " + dic.Key + ", " + source_angle.ToString());
                        //this.BeginInvoke(new ThreadStart(delegate
                        //{
                        //    ctl_frm_message.Show();
                        //}));


                        for (int k = 0; k < m_dtTestItem.Rows.Count; k++)
                        {
                            string m_sPortA_RCUIPort = m_dtTestItem.Rows[k][clsTestItem.chn_PortA_RCU].ToString();
                            string m_sPortA_RCUIndex = m_sPortA_RCUIPort.Substring(0, m_sPortA_RCUIPort.Length - GDefine.RCU_PORT_NAME.Length);
                            if (dic.Key == m_sPortA_RCUIndex)
                            {
                                FrmTips ctl_frm_message = new FrmTips("正在RCU调度: " + dic.Key + ", " + source_angle.ToString());
                                this.BeginInvoke(new ThreadStart(delegate
                                {
                                    ctl_frm_message.Show();
                                }));

                                bool ret = m_rcuObj.revertAngle(dic.Value, source_angle, source_speed);

                                this.Invoke(new ThreadStart(delegate
                                {
                                    ctl_frm_message.Close();
                                    ctl_frm_message = null;
                                }));

                                isrev = ret;
                                break;
                            }
                        }

                        //bool ret = m_rcuObj.revertAngle(dic.Value, source_angle, source_speed);


                        //this.Invoke(new ThreadStart(delegate
                        //{
                        //    ctl_frm_message.Close();
                        //    ctl_frm_message = null;
                        //}));

                        if (!isrev)
                        {
                            this.Invoke(new ThreadStart(delegate
                            {
                                tb_Test.AppendText(m_rcuObj.cmd.Substring(0, m_rcuObj.cmd.Length));
                                tb_Test.AppendText(m_rcuObj.result);
                            }));

                            return false;
                        }
                    }

                    this.Invoke(new ThreadStart(delegate
                    {
                        tb_Test.AppendText("RCU: set angel=" + source_angle / 10 + "\r\n");
                    }));

                    dic.Value.angle = source_angle;
                }
            }

            return true;
        }

        #endregion

        #region 上传

        private bool DataProcessCheck(ClsDataProduct product, ClsDataUser user)
        {
            if (!m_resultBuilder.constructSN(product.sProductSN, product.sPIMTestStep, user, true))
            {
                tb_Test.AppendText("resultData: 条码数据检测");
                return false;
            }

            if (!m_resultBuilder.isEnable)
            {
                tb_Test.AppendText("resultData: 上传数据功能未启用");
            }
            else
            {
                tb_Test.AppendText("resultData: MOID=" + m_resultBuilder.m_sMOID + "\r\n");
                tb_Test.AppendText("resultData: ProductTypeID=" + m_resultBuilder.m_sProductTypeID + "\r\n");
                tb_Test.AppendText("resultData: ProductTypeName=" + m_resultBuilder.m_sProductTypeName + "\r\n");
            }
            return true;
        }

        private void combineDataUpload(int iTestType, ref bool b, ref string sTime)
        {
            if (!m_resultBuilder.downloadOtherElecTempNEW(iTestType))
            {
                if (m_resultBuilder.uploadElecTempNew(m_dtTestItem, m_dicResult, ref b))
                {
                    tb_Test.AppendText("resultData: 上传临时数据成功\r\n");
                }
                else
                {
                    tb_Test.AppendText("resultData: 上传临时数据失败\r\n");
                }
            }
            else
            {
                if (m_resultBuilder.uploadElecNew(m_dtTestItem, m_dicResult, ref b, ref sTime))
                {
                    tb_Test.AppendText("resultData: 上传当前数据成功\r\n");
                }
                else
                {
                    tb_Test.AppendText("resultData: 上传当前数据失败\r\n");
                    return;
                }

                if (m_resultBuilder.uploadOtherElecTempNew(iTestType, sTime))
                {
                    tb_Test.AppendText("resultData: 上传其他数据成功\r\n");
                }
                else
                {
                    tb_Test.AppendText("resultData: 上传其他数据失败\r\n");
                    return;
                }

                if (m_resultBuilder.updateElecTempNew())
                {
                    tb_Test.AppendText("resultData: 屏蔽临时数据成功\r\n");
                }
                else
                {
                    tb_Test.AppendText("resultData: 屏蔽临时数据失败\r\n");
                    return;
                }
            }
        }
        bool combineDataUpload(int iTestType, ref bool b, ref string sTime, int id)
        {
            if (!m_resultBuilder.downloadOtherElecTempNEW(iTestType))
            {
                if (m_resultBuilder.uploadElecTempNew(m_dtTestItem, m_dicResult, ref b))
                {
                    tb_Test.AppendText("resultData: 上传临时数据成功\r\n");
                    MessageBox.Show("上传临时数据成功");
                    return true;
                }
                else
                {
                    tb_Test.AppendText("resultData: 上传临时数据失败\r\n");
                    MessageBox.Show("上传临时数据失败");
                    return false;
                }
            }
            else
            {
                if (DataUpload(ref id, ref sTime))
                {
                    if (m_resultBuilder.uploadElecNew(m_dtTestItem, m_dicResult, ref b, ref sTime, id))
                    {
                        tb_Test.AppendText("resultData: 上传当前数据成功\r\n");
                        MessageBox.Show("上传当前数据成功");
                    }
                    else
                    {
                        tb_Test.AppendText("resultData: 上传当前数据失败\r\n");
                        MessageBox.Show("上传当前数据失败");
                        return false;
                    }

                    if (m_resultBuilder.uploadOtherElecTempNew(iTestType, sTime))
                    {
                        tb_Test.AppendText("resultData: 上传其他数据成功\r\n");
                        MessageBox.Show("上传其他数据成功");
                    }
                    else
                    {
                        tb_Test.AppendText("resultData: 上传其他数据失败\r\n");
                        MessageBox.Show("上传其他数据失败");
                        return false;
                    }

                    if (m_resultBuilder.updateElecTempNew())
                    {
                        tb_Test.AppendText("resultData: 屏蔽临时数据成功\r\n");
                        MessageBox.Show("屏蔽临时数据成功");
                    }
                    else
                    {
                        tb_Test.AppendText("resultData: 屏蔽临时数据失败\r\n");
                        MessageBox.Show("屏蔽临时数据失败");
                        return false;
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        private void DataProcessUpload()
        {
            if (m_AntennaType == AntennaType.NUMAL)
            {
                m_rcuObj.output_message(m_productObj, m_usrObj.aUser, m_dicRCUs, type);
            }
            string sLog = "\r\n";
            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {
                float value = 0;
                if (m_dicResult.ContainsKey(i))
                    value = m_dicResult[i].fValue;
                sLog += string.Format("{0}\t{1}\t{2}\t{3}\r\n",
                                      i,
                                      m_dtTestItem.Rows[i][clsTestItem.chn_ParamName],
                                      m_dtTestItem.Rows[i][clsTestItem.chn_Freq],
                                      value);
            }
            DataProcessSaveLocal(sLog + "\r\n");


            if (!m_resultBuilder.isEnable)
            {
                tb_Test.AppendText("resultData: 上传数据功能未启用\r\n");
                return;
            }
            bool b = false; string sTime = "";

            if (GDefine.IS_UploadFAD && m_AntennaType == AntennaType.TD)
            {
                tb_Test.AppendText("resultData: FAD天线测试数据不上传\r\n");
                return;
            }
            if (!GDefine.IS_UploadElecNew)
            {
                if (m_AntennaType == AntennaType.TD)
                {
                    if (m_lstTestType.Count > 1)
                    {
                        if (!m_isTestAmPh)
                        {
                            combineDataUpload((int)AntennaTestType.AmplitudePhase, ref b, ref sTime);
                        }
                        else if (!m_isTestIso)
                        {
                            combineDataUpload((int)AntennaTestType.InterbandIsolation, ref b, ref sTime);
                        }
                        else
                        {
                            MessageBox.Show("无测试项目");
                        }
                    }
                    else
                    {
                        if (m_resultBuilder.uploadElecNew(m_dtTestItem, m_dicResult, ref b, ref sTime))
                        {
                            tb_Test.AppendText("resultData: 上传数据成功\r\n");
                        }
                        else
                        {
                            tb_Test.AppendText("resultData: 上传数据失败\r\n");
                        }
                    }
                }
                else
                {
                    if (m_resultBuilder.uploadElecNew(m_dtTestItem, m_dicResult, ref b, ref sTime))
                    {
                        tb_Test.AppendText("resultData: 上传数据成功\r\n");
                    }
                    else
                    {
                        tb_Test.AppendText("resultData: 上传数据失败\r\n");
                    }
                }
            }
            else
            {
                if (m_resultBuilder.uploadElec(m_dtTestItem, m_dicResult, ref b))
                {
                    tb_Test.AppendText("resultData: 上传数据成功\r\n");
                }
                else
                {
                    tb_Test.AppendText("resultData: 上传数据失败\r\n");
                }
            }
        }
        private void DataProcessUploadNew()
        {
            if (m_AntennaType == AntennaType.NUMAL)
            {
                m_rcuObj.output_message(m_productObj, m_usrObj.aUser, m_dicRCUs, type);
            }
            string sLog = "\r\n";
            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {
                float value = 0;
                if (m_dicResult.ContainsKey(i))
                    value = m_dicResult[i].fValue;
                sLog += string.Format("{0}\t{1}\t{2}\t{3}\r\n",
                                      i,
                                      m_dtTestItem.Rows[i][clsTestItem.chn_ParamName],
                                      m_dtTestItem.Rows[i][clsTestItem.chn_Freq],
                                      value);
            }
            DataProcessSaveLocal(sLog + "\r\n");


            if (!m_resultBuilder.isEnable)
            {
                tb_Test.AppendText("resultData: 上传数据功能未启用\r\n");
                MessageBox.Show("上传数据功能未启用");
                return;
            }
            bool b = false;
            int id = 0;
            string sTime = "";
            if (GDefine.IS_UploadFAD && m_AntennaType == AntennaType.TD)
            {
                tb_Test.AppendText("resultData: FAD天线测试数据不上传\r\n");
                return;
            }

            for (int tryNum = 0; tryNum < 1; tryNum++)
            {
                bool isSucceed = true;
                if (!GDefine.IS_UploadElecNew)
                {
                    if (m_AntennaType == AntennaType.TD)
                    {
                        if (m_lstTestType.Count > 1)
                        {
                            if (!m_isTestAmPh)
                            {
                                if (!combineDataUpload((int)AntennaTestType.AmplitudePhase, ref b, ref sTime, id))
                                    isSucceed = false;
                            }
                            else if (!m_isTestIso)
                            {
                                if (!combineDataUpload((int)AntennaTestType.InterbandIsolation, ref b, ref sTime, id))
                                    isSucceed = false;
                            }
                            else
                            {
                                MessageBox.Show("无测试项目");
                            }
                        }
                        else
                        {
                            if (DataUpload(ref id, ref sTime))
                            {
                                if (m_resultBuilder.uploadElecNew(m_dtTestItem, m_dicResult, ref b, ref sTime, id))
                                {
                                    tb_Test.AppendText("resultData: 上传数据成功\r\n");
                                    MessageBox.Show("上传数据成功");
                                }
                                else
                                {
                                    tb_Test.AppendText("resultData: 上传数据失败\r\n");
                                    MessageBox.Show("上传数据失败");
                                    isSucceed = false;
                                }
                            }
                            else
                            {
                                tb_Test.AppendText("resultData: 上传数据失败\r\n");
                                MessageBox.Show("上传数据失败");
                                isSucceed = false;
                            }
                        }
                    }
                    else
                    {
                        if (DataUpload(ref id, ref sTime))
                        {
                            if (m_resultBuilder.uploadElecNew(m_dtTestItem, m_dicResult, ref b, ref sTime, id))
                            {
                                tb_Test.AppendText("resultData: 上传数据成功\r\n");
                                MessageBox.Show("上传数据成功");
                            }
                            else
                            {
                                tb_Test.AppendText("resultData: 上传数据失败\r\n");
                                MessageBox.Show("上传数据失败");
                                isSucceed = false;
                            }
                        }
                        else
                        {
                            tb_Test.AppendText("resultData: 上传数据失败\r\n");
                            MessageBox.Show("上传数据失败");
                            isSucceed = false;
                        }
                    }
                }
                else
                {
                    if (m_resultBuilder.uploadElec(m_dtTestItem, m_dicResult, ref b))
                    {
                        tb_Test.AppendText("resultData: 上传数据成功\r\n");
                        MessageBox.Show("上传数据成功");
                    }
                    else
                    {
                        tb_Test.AppendText("resultData: 上传数据失败\r\n");
                        MessageBox.Show("上传数据失败");
                        isSucceed = false;
                    }
                }

                if (!isSucceed)
                {
                    if (MessageBox.Show("上传数据失败，是否重试", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    {
                        tryNum--;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
        }
        private bool DataProcessCalRCU()
        {
            if (m_Instr.RCU_Type == 0) return true;
            if (DEBUG_TEST) return true;

            string sResult = "PASS";
            var dicRCU = getListRCU();
            if (dicRCU == null)
            {
                sResult = "FAIL";
            }
            else
            {
                foreach (var rcu in dicRCU)
                {
                    tb_Test.AppendText(rcu.Key + ": " + rcu.Value.angle + "\r\n");
                    if (rcu.Value.angle == -1)
                    {
                        sResult = "FAIL";
                    }
                }
            }

            ClsDataRCUCheckBuilder rcuCheck = new ClsDataRCUCheckBuilder(GDefine.DBNameELEC);
            rcuCheck.construct(tbProSN.Text);
            if (rcuCheck.updateStatus(sResult))
            {
                tb_Test.AppendText("calibrationData: 上传校准数据成功\r\n");
            }
            else
            {
                tb_Test.AppendText("calibrationData: 上传校准数据失败\r\n");
            }

            return sResult == "PASS";
        }
        private bool CalRcu()
        {
            if (m_Instr.RCU_Type == 0) return true;
            if (DEBUG_TEST) return true;

            string sResult = "PASS";
            var dicRCU = getListRCU();
            if (dicRCU == null)
            {
                sResult = "FAIL";
            }
            else
            {
                foreach (var rcu in dicRCU)
                {
                    tb_Test.AppendText(rcu.Key + ": " + rcu.Value.angle + "\r\n");
                    if (rcu.Value.angle == -1)
                    {
                        sResult = "FAIL";
                    }
                }
            }
            return sResult == "PASS";
        }
        private bool UploadCalRcuStatus(ClsDataRCUCheck RCUCheck)
        {
            ClsDataRCUCheckBuilder rcuCheck = new ClsDataRCUCheckBuilder(GDefine.DBNameELEC);
            return rcuCheck.updateStatus(RCUCheck);
        }
        private void DataProcessSaveLocal(string msg)
        {
            Insert_Standard_ErrorLog.Insert(msg);
        }

        #endregion

        #region 测试

        private void setEnable(bool enable)
        {
            groupBox1.Enabled = enable;
            groupBox3.Enabled = enable;
        }

        private void tbProSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                btn_Start_Click(sender, e);
            }
        }

        private void btn_Start_Click(object sender, EventArgs e)
        {
            if (!m_IsRun)
            {
                btn_Start.Enabled = false;
                BtnInstr.Enabled = false;
                setEnable(false);
                tb_Test.Clear();
                m_bNeedQuit = false;
                if (!m_IsVNADebug)
                {
                    tb_Test.AppendText("正在连接仪表...\r\n");
                    if (!ConnectionTest())
                    {//如果连接失败弹出连接配置框
                        btn_Start.Enabled = true;
                        BtnInstr.Enabled = true;
                        setEnable(true);
                        btn_Start.Focus();
                        tb_Test.AppendText("连接仪表失败.\r\n");
                        return;
                    }
                    tb_Test.AppendText("连接仪表成功.\r\n");
                }

                this.btn_Start.Enabled = true;
                btn_Start.Focus();
                //mustdo 测试与开关箱链路的关系必须理清
                //if (m_Instr.Switch_Type == (int)SwitchType.SWITCH_NONE)
                //{
                //    m_TestTimes = 1;
                //}
                //else
                //{
                //    m_TestTimes = 1;
                //}

                #region 初始化测试数据

                m_productObj = new ClsDataProduct();
                m_productObj.sProductSN = tbProSN.Text;

                if (!m_isLocalConfg)
                {//数据库
                    //productObj.sProcode = ctl_main_cbProCode.Text;
                    if (!m_resultBuilder.matchSN(m_productObj))
                    {//匹配条码
                        MessageBox.Show("该条码无法匹配产品代码!");
                        tb_Test.AppendText("resultData: 该条码无法匹配产品代码");
                        btn_Start.Enabled = true;
                        ShowTestOff(null, null);
                        return;
                    }

                    ClsDataConfigSelectBuilder m_selectBuilder = new ClsDataConfigSelectBuilder(GDefine.DBNameELEC);
                    m_selectBuilder.construct(m_productObj.sMOID);
                    List<bool> lstEnable = m_selectBuilder.downloadELECSelect();
                    if (lstEnable == null)
                    {//查询配置可选
                        MessageBox.Show("该条码无法查询配置可选!");
                        tb_Test.AppendText("resultData: 该条码无法查询配置可选");
                        btn_Start.Enabled = true;
                        ShowTestOff(null, null);
                        return;
                    }
                    m_productObj.enableConfig = lstEnable;

                    m_usrObj.aSpecial = m_selectBuilder.downladSpecial();
                    if (m_usrObj.aSpecial == null)
                    { //查询数据特采
                        MessageBox.Show("该条码无法查询数据特采!");
                        tb_Test.AppendText("resultData: 该条码无法查询数据特采");
                        btn_Start.Enabled = true;
                        ShowTestOff(null, null);
                        return;
                    }

                    ClsDataRcuConfigBuilder m_rcuCfgBuilder = new ClsDataRcuConfigBuilder(GDefine.DBNameELEC);
                    m_rcuCfgBuilder.constructByProcode(m_productObj.sProcode);
                    if (m_rcuCfgBuilder.construct(m_productObj.sProcode, "1.0"))
                    {
                        m_productObj.rcuConfig = m_rcuCfgBuilder.download();
                    }

                    if (cbProCode.Text == m_productObj.sProcode)
                    {//获取配置
                        cbProCode_SelectedIndexChanged(null, null);
                    }
                    else
                    {
                        if (cbProCode.Items.IndexOf(m_productObj.sProcode) < 0)
                        {//刷新缓存
                            initDataConfig();
                        }
                        cbProCode.Text = m_productObj.sProcode;
                    }
                }
                else
                {//本地
                    m_productObj.sProcode = cbProCode.Text.Substring(cbProCode.Text.LastIndexOf('\\') + 1);
                    m_productObj.enableConfig = m_enableConfig;
                    SetDgvDataSource();
                }


                ClsDataCalResult calRes = new ClsDataCalResult(GDefine.DBNameELEC);
                if (!calRes.isPassCal(m_usrObj.sEquID))
                {
                    MessageBox.Show("仪器未校准！");
                    btn_Start.Enabled = true;
                    ShowTestOff(null, null);
                    return;
                }

                if (m_dtTestItem == null || m_dtTestItem.Rows.Count == 0)
                {
                    MessageBox.Show("产品代码的配置为空或不存在!");
                    btn_Start.Enabled = true;
                    ShowTestOff(null, null);
                    return;
                }


                if (m_productObj.enableConfig.Count == 0)
                {//无配置时
                    // m_productObj.enableConfig.Clear();
                    for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
                        m_productObj.enableConfig.Add(true);
                }
                else
                {
                    if (m_dtTestItem.Rows.Count != m_productObj.enableConfig.Count)
                    {//配置数量错误
                        MessageBox.Show("产品代码的可选配置错误！");
                        btn_Start.Enabled = true;
                        ShowTestOff(null, null);
                        return;
                    }

                    dgvTest.CurrentCell = null;
                    for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
                    {//配置可选
                        dgvTest.Rows[i].Visible = m_productObj.enableConfig[i];
                        if (m_productObj.enableConfig[i])
                            dgvTest.CurrentCell = dgvTest.Rows[i].Cells[0];
                    }
                }


                m_productObj.enableTestItem = new List<bool>();
                for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
                {
                    m_productObj.enableTestItem.Add(true);
                }
                m_lstTestType.Clear();
                if (m_AntennaType == AntennaType.TD)
                {
                    if (m_Procode != m_productObj.sProcode)
                    {
                        m_Procode = m_productObj.sProcode;
                        FrmTestTypeSelect frm = new FrmTestTypeSelect(m_isTestIso, m_isTestAmPh);
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            m_isTestIso = frm.isTestIso;
                            m_isTestAmPh = frm.isTestAmPh;
                        }
                    }
                    if (!m_isTestIso || !m_isTestAmPh)
                    {
                        //与货币管理器的位置关联的行不能设置为不可见异常解决方案  
                        //CurrencyManager myCM = (CurrencyManager)BindingContext[dgvTest.DataSource];
                        //myCM.SuspendBinding();//挂起数据绑定  
                        dgvTest.CurrentCell = null;
                        for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
                        {
                            int type = Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sTestType].ToString());
                            if (m_lstTestType.IndexOf(type) < 0)
                            {
                                m_lstTestType.Add(type);
                            }
                            if (!m_isTestIso && type == (int)AntennaTestType.InterbandIsolation)
                            {
                                m_productObj.enableTestItem[i] = false;
                                dgvTest.Rows[i].Visible = m_productObj.enableTestItem[i];
                            }
                            else if (!m_isTestAmPh && type == (int)AntennaTestType.AmplitudePhase)
                            {
                                m_productObj.enableTestItem[i] = false;
                                dgvTest.Rows[i].Visible = m_productObj.enableTestItem[i];
                            }
                            if (m_productObj.enableTestItem[i] && m_productObj.enableConfig[i])
                            {
                                dgvTest.CurrentCell = dgvTest.Rows[i].Cells[0];
                            }
                        }
                        //myCM.ResumeBinding();//恢复数据绑定      
                        //myCM = null;

                        if (m_productObj.enableTestItem.IndexOf(true) < 0)
                        {
                            MessageBox.Show("已全部筛选！无测试项！测试停止!");
                            btn_Start.Enabled = true;
                            ShowTestOff(null, null);
                            return;
                        }
                    }
                }


                m_productObj.sPIMTestStep = cbELECStep.SelectedItem.ToString();
                if (!DataProcessCheck(m_productObj, m_usrObj))
                {//检测工序
                    if (m_resultBuilder.error() != "")
                        MessageBox.Show(m_resultBuilder.error());
                    btn_Start.Enabled = true;
                    ShowTestOff(null, null);
                    return;
                }

                if (m_rcuObj != null)
                    m_rcuObj.record_SN(m_productObj.sProductSN);

                m_iSpeed = Convert.ToInt32(ctl_main_nudSpeed.Value);
                m_dicResult.Clear();
                //SetDgvDataSource();
                btn_Start.Text = "停止";
                #endregion

                tb_Test.AppendText("-------------------正常模式------------------\r\n");
                m_bNeedQuit = false;
                m_Continue_lsTraceTested.Clear();//清除缓存
                m_arrTrace_temp.Clear();
                m_RevertAngle = cbRebootStatus.SelectedIndex;

                //if (m_AntennaTestType == AntennaType.TD)
                //{
                //    m_TestThread = new Thread(TestStartTD);
                //}
                //else if (m_AntennaTestType == AntennaType.MIX)
                //{

                //}
                //else
                //{
                m_TestThread = new Thread(TestStart);
                //}
                m_IsRun = true;
                m_TestThread.Start();
            }
            else
            {
                if (MessageBox.Show("正在测试中，确认要终止测试?", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                    return;
                m_bNeedQuit = true;
            }
        }

        void TestStartTD()
        {
            TestBuliderTD();
        }


        Dictionary<int, PIM_ATE.Electrical.TestPortInfo> m_INTdicTestPortsTD;
        void TestBuliderTD()
        {
            Dictionary<string, PIM_ATE.Electrical.TestPortInfo> m_dicTestPortsTD = new Dictionary<string, TestPortInfo>();
            List<int> TestIndex = new List<int>();
            List<string> TestTip = new List<string>();
            int ChangeTime = 0;
            List<string> lstRCU = new List<string>();
            List<string> lstAngle = new List<string>();
            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {//取出测试端口 
                TestIndex.Add(-1);
                TestTip.Add("-1");
                //   if (m_dtTestItem.Rows[i][clsTestItem.chn_PortA].ToString() == "-1") { continue; }
                string rcuName1 = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                string rcu1 = rcuName1.Split('-')[0];
                string agl1 = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString();

                PIM_ATE.Electrical.TestPortInfo info = new TestPortInfo();
                info.lstAngle = new List<string>();//TD测试未使用此属性  可不要
                info.lstTestPort = new List<string>();
                if (!m_dicTestPortsTD.ContainsKey(rcu1))
                {
                    m_dicTestPortsTD.Add(rcu1, info);
                }
                foreach (var rcu in m_dicTestPortsTD)
                {
                    if (rcu.Key == rcu1)
                    {
                        if (rcu.Value.lstTestPort.IndexOf(rcuName1) < 0)
                        {
                            rcu.Value.lstTestPort.Add(rcuName1);
                        }
                        if (rcu.Value.lstTestPort.IndexOf(rcuName1) > -1 && rcu.Value.lstAngle.IndexOf(agl1) < 0)
                        {
                            rcu.Value.lstAngle.Add(agl1);
                        }
                    }
                }
            }


            #region 排列 测试角度顺序--配置构建完成  此处不处理
            //for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            //{//排列
            //    string sPortA_RCUIPort = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
            //    string sPortA_RCUIndex = sPortA_RCUIPort.Substring(0, sPortA_RCUIPort.Length - GDefine.RCU_PORT_NAME.Length);

            //    string sPortB_RCUIPort = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
            //    string sPortB_RCUIndex = sPortB_RCUIPort.Substring(0, sPortB_RCUIPort.Length - GDefine.RCU_PORT_NAME.Length);

            //    string sPortA_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString();
            //    string sPortB_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Angle].ToString();

            //    int sTestNo = 0;
            //    foreach (var obj in m_dicTestPortsTD)
            //    {
            //        foreach (var s in obj.Value.lstAngle)
            //        {
            //            if (sPortA_Angle == s && sPortB_Angle == s)
            //            {
            //                m_dtTestItem.Rows[i][clsTestItem.chn_TestNo] = sTestNo;
            //                m_dtShow.Rows[i][clsTestItem.chn_TestNo] = sTestNo++;
            //            }
            //        }
            //    }
            //}
            //设置测试次数
            m_TestTimes = 3;
            #endregion


            //分组提取测试循环
            Dictionary<int, PIM_ATE.Electrical.TestPortInfo> dicPort = new Dictionary<int, TestPortInfo>();
            if (/*m_Instr.Switch_Type == (int)SwitchType.SWITCH_NONE && */m_dicTestPortsTD.Count * 8 <= m_Instr.Switch_Count)
            {
                PIM_ATE.Electrical.TestPortInfo tp = new TestPortInfo();
                tp.lstAngle = new List<string>();
                tp.lstTestPort = new List<string>();
                tp.lstTips = new List<string>();
                dicPort.Add(ChangeTime, tp);
                foreach (var va in m_dicTestPortsTD)
                {
                    dicPort[ChangeTime].lstAngle.AddRange(va.Value.lstAngle.ToArray());
                    dicPort[ChangeTime].lstTestPort.AddRange(va.Value.lstTestPort.ToArray());
                }
                ChangeTime++;
            }
            else
            {
                foreach (var va in m_dicTestPortsTD)
                {
                    dicPort.Add(ChangeTime++, va.Value);
                }
                if (m_dicTestPortsTD.Count * 8 > m_Instr.Switch_Count)
                {//测试端口大于矩阵端口进行带间隔离的分组
                    int count = m_Instr.Switch_Count / 2;
                    int ForCount = (int)Math.Ceiling((double)dicPort[0].lstTestPort.Count / count);
                    int index = 0, i = 0;
                    for (int j = 0; j < ForCount; j++)
                    {
                        PIM_ATE.Electrical.TestPortInfo info = new TestPortInfo();
                        info.lstTestPort = new List<string>();
                        info.lstAngle = new List<string>();
                        List<string> lstrcu = new List<string>();
                        List<string> lstagl = new List<string>();
                        foreach (var rcu in m_dicTestPortsTD)
                        {
                            lstagl = new List<string>();
                            i = 0;
                            foreach (var p in rcu.Value.lstTestPort)
                            {
                                i++;
                                if (p.ToUpper().Contains("CAL")) { i--; continue; }
                                if (i < index)
                                {
                                    continue;
                                }
                                if (i - index > count)
                                {
                                    break;
                                }
                                lstrcu.Add(p);
                            }
                            lstagl.AddRange(rcu.Value.lstAngle);
                        }
                        index = i;
                        info.lstTestPort.AddRange(lstrcu);
                        info.lstAngle.AddRange(lstagl);
                        dicPort.Add(ChangeTime++, info);
                    }
                }
            }

            m_INTdicTestPortsTD = dicPort;
            //各组接线提示
            foreach (var obj in dicPort)
            {//分组--端口接线
                obj.Value.lstTips = new List<string>();
                List<string> lsttip = new List<string>();
                int i = 0;
                foreach (var s in obj.Value.lstTestPort)
                {
                    lsttip.Add((i + 1).ToString());
                    i++;
                }
                obj.Value.lstTips.AddRange(lsttip.ToArray());
            }
            foreach (var obj in dicPort)
            {//分布接线
                int IndexA = 0;
                foreach (var a in obj.Value.lstTestPort)
                {
                    for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
                    {
                        if (TestTip[i] != "-1") continue;
                        string rcuName1 = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                        string rcuName2 = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString();
                        string portA = "";
                        string portB = "";
                        int IndexB = 0;

                        if (rcuName1 == a)
                        {
                            portA = obj.Value.lstTips[IndexA].Split(',')[0];
                            foreach (var b in obj.Value.lstTestPort)
                            {
                                if (rcuName2 == b)
                                {
                                    portB = obj.Value.lstTips[IndexB].Split(',')[0];
                                    break;
                                }
                                IndexB++;
                            }
                            if (portB == "")
                            {
                                continue;
                            }
                        }
                        if (portA != "" && portB != "")
                        {
                            TestTip[i] = portA + "," + portB; //break;
                        }
                    }
                    IndexA++;
                }
            }
            //分组测试顺序分组轮循
            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {//分布测试顺序
                //if (!m_productObj.enableConfig[i] || !m_productObj.enableTestItem[i])
                //{
                //    continue;
                //}
                string rcuName1 = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                string rcuName2 = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString();
                foreach (var obj in dicPort)
                {
                    foreach (var s in obj.Value.lstTestPort)
                    {
                        if ((rcuName1 == s && obj.Value.lstTestPort.IndexOf(rcuName2) > -1 && TestIndex[i] == -1) || (rcuName2 == s && obj.Value.lstTestPort.IndexOf(rcuName1) > -1 && TestIndex[i] == -1))
                            TestIndex[i] = obj.Key;
                    }
                }
            }
            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {
                //m_dtTestItem.Rows[i]["测试顺序"] = TestIndex[i];
                m_dtTestItem.Rows[i][clsTestItem.chn_Index] = TestIndex[i];
                if (TestTip[i].Split(',').Length < 2) continue;
                m_dtTestItem.Rows[i][clsTestItem.chn_PortA] = TestTip[i].Split(',')[0];
                m_dtTestItem.Rows[i][clsTestItem.chn_PortB] = TestTip[i].Split(',')[1];
            }
            m_ChangeTimes = dicPort.Count - 1;

        }

        void TestStart()
        {
            m_SNcheckPass = true;
            m_WavefromPass = true;
            m_RcuCalPass = true;
            m_AllTestItemPass = true;

            #region RCU初始化
            if (m_AntennaType == AntennaType.NUMAL)
            {
                if (!ConnectionRCU())
                {
                    this.Invoke(new ThreadStart(delegate
                    {
                        btn_Start.Enabled = true;
                        BtnInstr.Enabled = true;
                        //btn_Start.Focus();
                        ShowTestOff(null, null);
                    }));
                    this.Invoke(new EventHandler(ShowText), "\r\n结束！\r\n\r\n");
                    this.Invoke(new ThreadStart(delegate { DataProcessUploadNew(); }));
                    return;
                }
            }
            #endregion

            m_iTimeStart = DateTime.Now;
            this.Invoke(new EventHandler(ShowText),
                m_iTimeStart.ToString() + "\r\n开始！产品编号：" + tbProSN.Text + "\r\n");
            bool bTestFull = true;//测试了所有项目
            m_bManualStop = false;
            m_bTotalResult = true;

            /***************天线端口大于矩阵或矢网端口***************************/
            if (m_AntennaType == AntennaType.NUMAL)
            {
                TestBulider();
            }
            else if (m_AntennaType == AntennaType.TD)
            {
                TestBuliderTD();
            }
            /***************天线端口大于矩阵或矢网端口***************************/

            bool blAllTested = false;
            for (int iChange = 0; iChange < m_ChangeTimes + 1; iChange++)
            {//根据开关箱统一切换  频段（RCU端口） 分组轮循

                #region 提示
                if (m_Instr.Switch_Type != 0)
                {
                    List<string> lstTips = new List<string>();
                    for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
                    {
                        if (m_dtTestItem.Rows[i][clsTestItem.chn_Index].ToString() != iChange.ToString() || !m_productObj.enableConfig[i] || !m_productObj.enableTestItem[i])
                            continue;
                        string t1 = ""; string t2 = "";
                        if (m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Tip].ToString() == "" || m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Tip].ToString() == "")
                        {
                            t1 = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString() + " ==> 开关端口 " +
                                    m_dtTestItem.Rows[i][clsTestItem.chn_PortA] + "\r\n";
                            t2 = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString() + " ==> 开关端口 " +
                           m_dtTestItem.Rows[i][clsTestItem.chn_PortB] + "\r\n";
                        }
                        else
                        {
                            t1 = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Tip].ToString() + " ==> 开关端口 " +
                               m_dtTestItem.Rows[i][clsTestItem.chn_PortA] + "\r\n";
                            t2 = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Tip].ToString() + " ==> 开关端口 " +
                                    m_dtTestItem.Rows[i][clsTestItem.chn_PortB] + "\r\n";
                        }

                        if (lstTips.IndexOf(t1) < 0) lstTips.Add(t1);
                        if (lstTips.IndexOf(t2) < 0) lstTips.Add(t2);
                    }
                    string sTips = "请按如下提示接线:\r\n";
                    if (lstTips.Count == 0) continue;
                    foreach (var s in lstTips)
                    {
                        sTips += s;
                    }
                    MessageBox.Show(sTips);
                }
                #endregion

                /***************天线端口大于矩阵或矢网端口***************************/
                this.Invoke(new EventHandler(ShowText), "\r\n第" + (iChange + 1).ToString() + "组端口测试！请等待\r\n");
                if (m_AntennaType == AntennaType.NUMAL)
                {
                    if (iChange > 0 && m_Instr.Switch_Type != (int)SwitchType.SWITCH_NONE)
                    {//第二组---初始化角度
                        if (!RebootAgl(iChange, m_isInitMaxAngle)) { break; }
                    }
                }
                /***************天线端口大于矩阵或矢网端口***************************/

                for (int i = 1; i < m_TestTimes + 1; i++)
                {//角度
                    if (m_bNeedQuit) break;

                    /***************天线端口大于矩阵或矢网端口***************************/
                    if (m_AntennaType == AntennaType.NUMAL)
                    {
                        if (i == m_TestTimes && iChange > 0)
                        {//第三次  带间隔离(最大/最小)  换度
                            if (!RebootAgl(iChange, !m_isInitMaxAngle)) { break; }
                        }
                    }
                    /***************天线端口大于矩阵或矢网端口***************************/

                    if (m_AntennaType == AntennaType.TD)
                    {
                        if (!initRCUAngleTD(iChange, i)) break;
                    }

                    #region 提示
                    if (i != 1)
                    {//换线次数
                        //GetNameFrm diagramFrm = new GetNameFrm(m_dtSwitchLoad, i, m_curRemarkText, m_cProject.iCodeLen);
                        //if (MessageBox.Show("请换线开始第"+i+"测试","提示", MessageBoxButtons.OKCancel) != DialogResult.OK)
                        //{
                        //    bTestFull = false;
                        //    break;
                        //}
                    }
                    this.Invoke(new EventHandler(ShowText), "\r\n第" + (i).ToString() + "次调度测试！请等待\r\n");
                    #endregion

                    #region 开始测试
                    if (m_AntennaType == AntennaType.TD)
                    {
                        List<string> lstTestPortAB = new List<string>();
                        if (m_Instr.Switch_Type == 0)
                        {
                            for (int j = 0; j < m_dtTestItem.Rows.Count; j++)
                            {
                                int iChange1 = Convert.ToInt32(m_dtTestItem.Rows[j][clsTestItem.chn_Index].ToString().Trim());
                                int aglIndex = Convert.ToInt32(m_dtTestItem.Rows[j][clsTestItem.chn_TestNo].ToString().Trim());
                                string ItemName = m_dtTestItem.Rows[j][clsTestItem.chn_ItemName].ToString().Trim();

                                if (!m_productObj.enableConfig[j] || !m_productObj.enableTestItem[j] ||
                                    iChange1 != iChange || aglIndex != i /*||
                                     ItemName == "幅度一致性" || ItemName == "相位一致性"*/
                                    )
                                {
                                    continue;
                                }
                                string PortAB = m_dtTestItem.Rows[j][clsTestItem.chn_PortA_RCU].ToString() + ";" + m_dtTestItem.Rows[j][clsTestItem.chn_PortB_RCU].ToString();
                                if (lstTestPortAB.IndexOf(PortAB) < 0)
                                    lstTestPortAB.Add(PortAB);
                            }
                        }
                        bTestFull = ContTestTD(i, iChange, lstTestPortAB);
                        //delOthers(iChange, i);
                    }
                    else if (m_AntennaType == AntennaType.NUMAL)
                    {
                        bTestFull = ContTestNew(i, iChange);
                    }


                    if (!bTestFull) break;

                    #endregion
                }
                if (iChange == m_ChangeTimes)
                    blAllTested = true;
                if (!bTestFull) break;
            }

            //还原速度
            RCUProcessRebootStatue();

            //测试完成
            m_iTimeEnd = DateTime.Now;
            string sResultTips = "";

            if (!bTestFull && !m_bManualStop)
            {//测试一半且非手动结束的不保存
                this.Invoke(new EventHandler(ShowText), "\r\n测试结果： 测试被终止\r\n");
                sResultTips = "测试被终止";
                this.Invoke(new ThreadStart(delegate { MessageBox.Show(sResultTips); }));
                this.Invoke(new EventHandler(ShowText), "完成！" + m_iTimeEnd.ToString() + "\r\n\r\n");
                this.Invoke(new EventHandler(ShowTestOff));
                return;
            }

            if (m_bTotalResult)
            {//保存数据的动作也需要发消息来完成，否则会导致保存时数据还没到达
                //this.BeginInvoke(new EventHandler(SaveTestResultToDB), null);
                this.Invoke(new EventHandler(ShowText), "\r\n测试结果： PASS\r\n");
                sResultTips = "测试完成， 结果： PASS";
            }
            else
            {
                this.Invoke(new EventHandler(ShowText), "\r\n测试结果： FAIL\r\n");
                sResultTips = "测试完成， 结果： FAIL";
            }


            //this.Invoke(new ThreadStart(delegate
            //{
            //    for (int i = 0; i < 1; i++)
            //    {
            //        if (!DataProcessCalRCU())
            //        {//检测校准状态
            //            if (m_bTotalResult)
            //            {//指标合格的话重试
            //                if (MessageBox.Show("检测天线模块状态失败，请重试", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            //                {
            //                    i--;
            //                    continue;
            //                }
            //            }
            //            sResultTips = "测试失败，天线模块出现未校准情况, \r\n结果: FAIL";
            //        }
            //        else
            //        {//上传电性能数据
            //            DataProcessUpload();
            //            if (m_Instr.RCU_Type != 0)
            //            {
            //                MessageBox.Show("天线模块校准成功");
            //            }
            //        }
            //    }
            //}));

            this.Invoke(new ThreadStart(delegate { DataProcessUploadNew(); }));

            //this.Invoke(new ThreadStart(delegate { MessageBox.Show(sResultTips); }));
            this.Invoke(new EventHandler(ShowText), "完成！" + m_iTimeEnd.ToString() + "\r\n\r\n");
            this.Invoke(new EventHandler(ShowTestOff));
            this.Invoke(new EventHandler(ShowCursor));
        }

        bool DataUpload(ref int id, ref string sTime)
        {          
            //foreach (var obj in m_dicResult)
            //{
            //    if (obj.Value.sPass == "FAIL")
            //    {
            //        m_AllTestItemPass = false;
            //        break;
            //    }
            //}

            m_RcuCalPass = CalRcu();
            m_AllTestItemPass = m_bTotalResult;
            if (m_dicResult.Count == 0)
            {
                m_AllTestItemPass = m_bTotalResult = m_WavefromPass = m_RcuCalPass = false;
            }
            bool AllStatusPass = m_WavefromPass && m_SNcheckPass && m_AllTestItemPass && m_RcuCalPass;


            StringBuilder strB = new StringBuilder();
            string sNewLine = "\r\n";
            string sa = (AllStatusPass == true ? "整体测试合格" : "整体测试不合格") + sNewLine;
            string sb = (m_SNcheckPass == true ? "条码检测合格" : "条码检测不合格") + sNewLine;
            string sc = (m_WavefromPass == true ? "波形监控合格" : "波形监控不合格") + sNewLine;
            string sd = (m_RcuCalPass == true ? "RCU校准检测合格" : "RCU校准检测不合格") + sNewLine;
            string se = (m_AllTestItemPass == true ? "测试项指标合格" : "测试项指标不合格") + sNewLine;
            strB.AppendLine(sa);
            strB.AppendLine(sb);
            strB.AppendLine(sc);
            strB.AppendLine(sd);
            strB.AppendLine(se);
            tb_Test.AppendText(strB.ToString());
            MessageBox.Show(strB.ToString(), "Tips");

            DateTime time;
            ClsDataAllStatus AllStatus = new ClsDataAllStatus();
            AllStatus.ProductSN = m_productObj.sProductSN.ToUpper();
            AllStatus.Status = AllStatusPass == true ? GDefine.ContentPass : GDefine.ContentFail;
            if (!UploadAllStatus(AllStatus, out id, out time))
            {
                MessageBox.Show("上传数据(整体)失败", "Err");
                return false;
            }

            sTime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");

            if (m_Instr.RCU_Type != 0 && m_Instr.RCU_Check == 1)
            {
                ClsDataCodeStatus CodeStatus = new ClsDataCodeStatus();
                CodeStatus.ProductSN = m_productObj.sProductSN.ToUpper();
                CodeStatus.AllStatusId = id;
                CodeStatus.Time = time;
                CodeStatus.Status = m_SNcheckPass == true ? GDefine.ContentPass : GDefine.ContentFail;
                if (!UploadCodeStatus(CodeStatus))
                {
                    MessageBox.Show("上传数据(条码检测)失败", "Err");
                    return false;
                }
            }



            if (!m_SNcheckPass || m_dicResult.Count == 0)
            {
                //  MessageBox.Show("上传数据成功", "Tips");
                return true;
            }

            ClsDataWaveStatus WaveStatus = new ClsDataWaveStatus();
            WaveStatus.ProductSN = m_productObj.sProductSN.ToUpper();
            WaveStatus.AllStatusId = id;
            WaveStatus.Time = time;
            WaveStatus.Status = m_WavefromPass == true ? GDefine.ContentPass : GDefine.ContentFail;
            if (!UploadWaveStatus(WaveStatus))
            {
                MessageBox.Show("上传数据(波形监控)失败", "Err");
                return false;
            }

            if (m_Instr.RCU_Type != 0)
            {
                ClsDataRCUCheck rcucheck = new ClsDataRCUCheck();
                rcucheck.ProductSN = m_productObj.sProductSN.ToUpper();
                rcucheck.AllStatusId = id;
                rcucheck.Time = time;
                rcucheck.Status = m_RcuCalPass == true ? GDefine.ContentPass : GDefine.ContentFail;
                if (!UploadCalRcuStatus(rcucheck))
                {
                    MessageBox.Show("上传数据(RCU校准)失败", "Err");
                    return false;
                }
            }

            return true;
        }
        bool UploadAllStatus(ClsDataAllStatus Status, out int id, out DateTime time)
        {
            ClsDataAllStatusBuilder all = new ClsDataAllStatusBuilder(GDefine.DBNameELEC);
            all.construct(Status);
            bool res = all.updateStatus(out id, out time);
            return res;
        }
        bool UploadCodeStatus(ClsDataCodeStatus Status)
        {
            ClsDataCodeStatusBuilder all = new ClsDataCodeStatusBuilder(GDefine.DBNameELEC);
            all.construct(Status);
            bool res = all.updateStatus();
            return res;
        }
        bool UploadWaveStatus(ClsDataWaveStatus Status)
        {
            ClsDataWaveStatusBuilder all = new ClsDataWaveStatusBuilder(GDefine.DBNameELEC);
            all.construct(Status);
            bool res = all.updateStatus();
            return res;
        }
        void delOthers(int iChange, int i)
        {
            for (int j = 0; j < m_dtTestItem.Rows.Count; j++)
            {
                int bandIndex = Convert.ToInt32(m_dtTestItem.Rows[j][clsTestItem.chn_Index].ToString().Trim());
                int aglIndex = Convert.ToInt32(m_dtTestItem.Rows[j][clsTestItem.chn_TestNo].ToString().Trim());
                string ItemName = m_dtTestItem.Rows[j][clsTestItem.chn_ItemName].ToString().Trim();
                string mark = m_dtTestItem.Rows[j][clsTestItem.chn_sMarkers].ToString().Trim();
                if (!m_productObj.enableConfig[j] || !m_productObj.enableTestItem[j] ||
                    bandIndex != iChange || aglIndex != i/* ||
                    ItemName != "幅度一致性" || ItemName != "相位一致性"*/
                    )
                {
                    continue;
                }
                string PortAB = m_dtTestItem.Rows[j][clsTestItem.chn_PortA_RCU].ToString() + ";" + m_dtTestItem.Rows[j][clsTestItem.chn_PortB_RCU].ToString();
                if (ItemName == "幅度一致性" || ItemName == "相位一致性")
                {

                    #region 取值和预处理
                    int power = 10;
                    float InstrHigh = 999;
                    float InstrLow = 999;
                    clsTestItem arrTestItem = new clsTestItem();
                    arrTestItem.iTestIndex = j;
                    arrTestItem.sTestItem = m_dtTestItem.Rows[j][clsTestItem.chn_ItemName].ToString().Trim();
                    arrTestItem.sTestName = m_dtTestItem.Rows[j][clsTestItem.chn_ParamName].ToString().Trim();
                    arrTestItem.sFactSpec = m_dtTestItem.Rows[j][clsTestItem.chn_FactSpec].ToString().Trim();//内控要求 ≤1.43dB
                    arrTestItem.sInstrCtrl = m_dtTestItem.Rows[j][clsTestItem.chn_InstrCtrl].ToString();//仪表特殊控制
                    arrTestItem.sFreq = m_dtTestItem.Rows[j][clsTestItem.chn_Freq].ToString().Trim();//1830-1880MHz //Freq
                    arrTestItem.sRandom = m_dtTestItem.Rows[j][clsTestItem.chn_TestNo].ToString().Trim();//角度索引
                    arrTestItem.sTestFlag = m_dtTestItem.Rows[j][clsTestItem.chn_Done].ToString().Trim();
                    arrTestItem.sPortA = m_dtTestItem.Rows[j][clsTestItem.chn_PortA].ToString().Trim();//GetStrPortAB(iTestCount, );//1端口连接 ANT1//并对应开关切换表获得端口号，以便调用校准文件
                    arrTestItem.sPortB = m_dtTestItem.Rows[j][clsTestItem.chn_PortB].ToString().Trim();//GetStrPortAB(iTestCount, );//2端口连接 TXA1

                    arrTestItem.sTestPortType = m_dtTestItem.Rows[j][clsTestItem.chn_PortType].ToString().Trim();//测试内容 S21//GetSParamStr(
                    arrTestItem.sFormatType = m_dtTestItem.Rows[j][clsTestItem.chn_FormatType].ToString().Trim();//测试数据2 DISP_LOGM
                    arrTestItem.sReport = m_dtTestItem.Rows[j][clsTestItem.chn_Report].ToString().Trim();//报表内容 最小值的绝对值
                    arrTestItem.sBand = m_dtTestItem.Rows[j][clsTestItem.chn_Band].ToString().Trim();//校准带宽

                    arrTestItem.iTestCount = i;//角度索引
                    arrTestItem.power = power;

                    //RCU控制字段
                    arrTestItem.sPortA_Angle = m_dtTestItem.Rows[j][clsTestItem.chn_PortA_Angle].ToString().Trim();
                    arrTestItem.sPortB_Angle = m_dtTestItem.Rows[j][clsTestItem.chn_PortB_Angle].ToString().Trim();
                    arrTestItem.sPortA_RCU = m_dtTestItem.Rows[j][clsTestItem.chn_PortA_RCU].ToString().Trim();
                    arrTestItem.sPortB_RCU = m_dtTestItem.Rows[j][clsTestItem.chn_PortB_RCU].ToString().Trim();

                    arrTestItem.sPortA_Tip = m_dtTestItem.Rows[j][clsTestItem.chn_PortA_Tip].ToString().Trim();
                    arrTestItem.sPortB_Tip = m_dtTestItem.Rows[j][clsTestItem.chn_PortB_Tip].ToString().Trim();

                    arrTestItem.sTestFunction = m_dtTestItem.Rows[j][clsTestItem.chn_TestFunction].ToString().Trim();

                    //FAD
                    arrTestItem.sMarkers = m_dtTestItem.Rows[j][clsTestItem.chn_sMarkers].ToString().Trim();
                    arrTestItem.sAntennaType = Convert.ToInt16(m_dtTestItem.Rows[j][clsTestItem.chn_sAntennaType].ToString().Trim());
                    arrTestItem.sTestType = Convert.ToInt16(m_dtTestItem.Rows[j][clsTestItem.chn_sTestType].ToString().Trim());
                    arrTestItem.sTestMethod = Convert.ToInt16(m_dtTestItem.Rows[j][clsTestItem.chn_sTestMethod].ToString().Trim());

                    if (!GetFreqRange(arrTestItem.sFreq, ref arrTestItem.f1, ref arrTestItem.f2))
                    {//频率拆分新方法
                        MessageBox.Show("频率范围" + arrTestItem.sFreq + "解析失败,请参考'420MHz-2010MHz' ");
                        return;
                    }
                    #endregion


                    float maxV = float.MinValue, minV = float.MaxValue;
                    List<float> value = new List<float>();
                    for (int k = 0; k < m_dtTestItem.Rows.Count; k++)
                    {
                        int bandIndex1 = Convert.ToInt32(m_dtTestItem.Rows[j][clsTestItem.chn_Index].ToString().Trim());
                        int aglIndex1 = Convert.ToInt32(m_dtTestItem.Rows[j][clsTestItem.chn_TestNo].ToString().Trim());
                        string ItemName1 = m_dtTestItem.Rows[k][clsTestItem.chn_ItemName].ToString().Trim();
                        string mark1 = m_dtTestItem.Rows[k][clsTestItem.chn_sMarkers].ToString().Trim();

                        if (!m_productObj.enableConfig[k] || !m_productObj.enableTestItem[k] ||
                    bandIndex1 != iChange || aglIndex1 != i)
                        {
                            continue;
                        }

                        if (ItemName1 == "耦合")
                        {
                            if (mark == mark1)
                            {
                                if (m_dicResult.ContainsKey(k))
                                {
                                    maxV = maxV > m_dicResult[k].fValue ? maxV : m_dicResult[k].fValue;
                                    minV = minV < m_dicResult[k].fValue ? minV : m_dicResult[k].fValue;
                                    value.Add(m_dicResult[k].fValue);
                                }

                            }
                        }
                    }





                    bool bTotalResult = false;
                    bool bNowResult = DealResult(arrTestItem, maxV, minV, ref bTotalResult);
                }
                List<string> lstTestPortAB = new List<string>();
                if (lstTestPortAB.IndexOf(PortAB) < 0)
                    lstTestPortAB.Add(PortAB);


                //if (!m_dicResult.ContainsKey(aInsertRow.iRow))
                //{
                //    JcELECDataResults result = new JcELECDataResults();
                //    result.fValue = Convert.ToSingle(aInsertRow.sValue);
                //    result.sPass = aInsertRow.sResult;
                //    m_dicResult.Add(aInsertRow.iRow, result);
                //}
                //else
                //{
                //    m_dicResult[aInsertRow.iRow].fValue = Convert.ToSingle(aInsertRow.sValue);
                //    m_dicResult[aInsertRow.iRow].sPass = aInsertRow.sResult;
                //}
            }
        }
        Dictionary<int, PIM_ATE.Electrical.TestPortInfo> m_dicTestPorts;
        //List<int> TestIndex;
        void TestBulider()
        {//排列组合
            m_dicTestPorts = new Dictionary<int, TestPortInfo>();
            List<int> TestIndex = new List<int>();
            List<string> TestTip = new List<string>();
            int ChangeTime = 0;
            List<string> lstRCU = new List<string>();
            List<string> lstAngle = new List<string>();
            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {//取出测试端口
                if (m_dtTestItem.Rows[i][clsTestItem.chn_TestFunction].ToString() == "Continue")
                {
                    string rcuName1 = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                    rcuName1 = rcuName1.Substring(0, rcuName1.Length - GDefine.RCU_PORT_NAME.Length);
                    string agl = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString();
                    if (lstRCU.IndexOf(rcuName1) < 0)
                    {
                        lstRCU.Add(rcuName1);
                        lstAngle.Add(agl);
                    }
                }
                TestIndex.Add(-1);
                TestTip.Add("-1");
            }
            //分组
            dicTestPort(lstRCU, lstAngle, m_dicTestPorts, ChangeTime);

            foreach (var obj in m_dicTestPorts)
            {//分组--端口接线
                obj.Value.lstTips = new List<string>();
                List<string> lsttip = new List<string>();
                int i = 0;
                foreach (var s in obj.Value.lstTestPort)
                {
                    lsttip.Add((2 * i + 1) + "," + (2 * i + 1 + 1));
                    i++;
                }
                obj.Value.lstTips.AddRange(lsttip.ToArray());
            }

            foreach (var obj in m_dicTestPorts)
            {//分布接线
                int IndexA = 0;
                foreach (var a in obj.Value.lstTestPort)
                {
                    for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
                    {
                        if (TestTip[i] != "-1") continue;
                        string rcuName1 = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                        string rcuName2 = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString();
                        string portA = "";
                        string portB = "";
                        int IndexB = 0;

                        if (rcuName1 == (a + GDefine.RCU_PORT_NAME))
                        {
                            portA = obj.Value.lstTips[IndexA].Split(',')[0];
                            foreach (var b in obj.Value.lstTestPort)
                            {
                                if (rcuName2 == (b + GDefine.RCU_PORT_NAME))
                                {
                                    portB = obj.Value.lstTips[IndexB].Split(',')[0];
                                    break;
                                }
                                else if (rcuName2 == (b + GDefine.RCU_PORT_NAME_2))
                                {
                                    portB = obj.Value.lstTips[IndexB].Split(',')[1];
                                    break;
                                }
                                IndexB++;
                            }
                            if (portB == "")
                            {
                                continue;
                            }
                        }
                        else if (rcuName1 == (a + GDefine.RCU_PORT_NAME_2))
                        {
                            portA = obj.Value.lstTips[IndexA].Split(',')[1];
                            foreach (var b in obj.Value.lstTestPort)
                            {
                                if (rcuName2 == (b + GDefine.RCU_PORT_NAME))
                                {
                                    portB = obj.Value.lstTips[IndexB].Split(',')[0];
                                    break;
                                }
                                else if (rcuName2 == (b + GDefine.RCU_PORT_NAME_2))
                                {
                                    portB = obj.Value.lstTips[IndexB].Split(',')[1];
                                    break;
                                }
                                IndexB++;
                            }
                            if (portB == "")
                            {
                                continue;
                            }
                        }
                        if (portA != "" && portB != "")
                        {

                            TestTip[i] = portA + "," + portB; //break;
                        }
                    }
                    IndexA++;
                }
            }


            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {//分布测试顺序
                string rcuName1 = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                rcuName1 = rcuName1.Substring(0, rcuName1.Length - GDefine.RCU_PORT_NAME.Length);
                string rcuName2 = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString();
                rcuName2 = rcuName2.Substring(0, rcuName2.Length - GDefine.RCU_PORT_NAME.Length);
                foreach (var obj in m_dicTestPorts)
                {
                    foreach (var s in obj.Value.lstTestPort)
                    {
                        if ((rcuName1 == s && obj.Value.lstTestPort.IndexOf(rcuName2) > -1 && TestIndex[i] == -1) || (rcuName2 == s && obj.Value.lstTestPort.IndexOf(rcuName1) > -1 && TestIndex[i] == -1))
                            TestIndex[i] = obj.Key;
                    }
                }
            }

            //m_dtTestItem.Columns.Add("测试顺序");
            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {
                //m_dtTestItem.Rows[i]["测试顺序"] = TestIndex[i];
                m_dtTestItem.Rows[i][clsTestItem.chn_Index] = TestIndex[i];

                m_dtTestItem.Rows[i][clsTestItem.chn_PortA] = TestTip[i].Split(',')[0];
                m_dtTestItem.Rows[i][clsTestItem.chn_PortB] = TestTip[i].Split(',')[1];
            }
            m_ChangeTimes = m_dicTestPorts.Count - 1;

        }
        void dicTestPort(List<string> lstRCU, List<string> lstAngle, Dictionary<int, PIM_ATE.Electrical.TestPortInfo> m_dicTestPorts, int ChangeTime)
        {//分组
            if (lstRCU.Count * 2 > m_Instr.Switch_Count && m_Instr.Switch_Type != (int)SwitchType.SWITCH_NONE)
            {
                int index = 0;
                List<string> rcu = new List<string>();
                List<string> Rrcu = new List<string>();
                List<string> agl = new List<string>();
                List<string> Ragl = new List<string>();
                for (int i = index; i < m_Instr.Switch_Count / 2; i++)
                {
                    rcu.Add(lstRCU[index]);
                    agl.Add(lstAngle[index]);
                    index++;
                    if (i == m_Instr.Switch_Count / 2 - 1)
                    {
                        PIM_ATE.Electrical.TestPortInfo port = new TestPortInfo();
                        port.lstTestPort = new List<string>();
                        port.lstTestPort.AddRange(rcu.ToArray());
                        port.lstAngle = new List<string>();
                        port.lstAngle.AddRange(agl.ToArray());
                        m_dicTestPorts.Add(ChangeTime++, port);

                        Rrcu.Add(rcu[rcu.Count - 1]);
                        Ragl.Add(agl[agl.Count - 1]);

                        i--;
                        rcu.RemoveAt(rcu.Count - 1);
                        agl.RemoveAt(agl.Count - 1);
                    }
                    if (index >= lstRCU.Count)
                    {
                        List<string> newrcu = new List<string>();
                        newrcu.AddRange(Rrcu.ToArray());
                        List<string> newagl = new List<string>();
                        newagl.AddRange(Ragl.ToArray());
                        dicTestPort(newrcu, newagl, m_dicTestPorts, ChangeTime);
                        break;
                    }

                }
            }
            else
            {
                PIM_ATE.Electrical.TestPortInfo port = new TestPortInfo();
                port.lstTestPort = new List<string>();
                port.lstTestPort.AddRange(lstRCU.ToArray());
                port.lstAngle = new List<string>();
                port.lstAngle.AddRange(lstAngle.ToArray());
                m_dicTestPorts.Add(ChangeTime++, port);
            }
        }
        bool RebootAgl(int iChange, bool isInitMaxAngle)
        {
            bool ret = true;
            FrmTips ctl_frm_message = new FrmTips("RCU换度中....");
            if (m_Instr.RCU_Type != 0)
            {
                this.BeginInvoke(new ThreadStart(delegate
                {
                    ctl_frm_message.Show();
                    tb_Test.AppendText("正在初始化RCU...\r\n");
                }));
            }

            PIM_ATE.Electrical.TestPortInfo portinfo = m_dicTestPorts[iChange];
            string sMaxAngle = "";
            string sMinAngle = "";
            int index = 0;
            foreach (var port in portinfo.lstTestPort)
            {
                //bool isOneAngle = false;
                Regex reg = new Regex(@"(\d+|-\d+)-(\d+|-\d+)");
                string agl = portinfo.lstAngle[index++];
                var m = reg.Match(agl);
                if (m.Success && m.Groups.Count == 3)
                {
                    sMaxAngle = m.Groups[2].Value;
                    sMinAngle = m.Groups[1].Value;
                }
                else
                {
                    MessageBox.Show("配置文件中角度设置错误,请检查!");
                    ret = false;
                    break;
                }
                int iMaxAngle = Convert.ToInt32(sMaxAngle);
                int iMinAngle = Convert.ToInt32(sMinAngle);

                //if (iMaxAngle == iMinAngle) isOneAngle = true;

                int iNeedAngle = isInitMaxAngle ? iMaxAngle : iMinAngle;
                if (m_dicRCUs[port].angle != iNeedAngle * 10)
                {//已转度的-->还原角度   未转度的--->设置角度                    
                    if (m_Instr.RCU_Type != 0)
                    {
                        for (int tryNum = 0; tryNum < 1; tryNum++)
                        {
                            if (!setRCUIndex(port, iNeedAngle))
                            {
                                if (MessageBox.Show("RCU调度失败，是否重试", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                                {//重新开始,降低速度
                                    tryNum--;
                                }
                                else
                                {
                                    //break;
                                    ret = false;
                                }
                            }
                            Thread.Sleep(100);
                        }
                    }
                    else
                    {
                        setRCUIndex(port, iNeedAngle);
                        MessageBox.Show(port + " 手动调度 ==> " + iNeedAngle + "\r\n" + "当完成调度后，点击确定！");
                    }
                }
            }
            this.Invoke(new ThreadStart(delegate
            {
                if (!ret)
                    tb_Test.AppendText("RCU调度失败.\r\n");
                else
                    tb_Test.AppendText("RCU调度成功.\r\n");

                ctl_frm_message.Close();
                ctl_frm_message = null;
            }));
            return ret;
        }
        bool ContTest(int iTestCount, int iChangeCount)
        {//如果iTestCount = 0表示手动换线，1表示第一次换线，2表示第二次换线，以此类推  
            m_arrTrace_temp.Clear();

            int iGetValueMode = 0;//取值模式
            //bool bSegmentTestMode = false;//从Segment table 中取值标志
            bool bSameCalFileTest = false;//相同的校准文件统一读值标志
            StringBuilder sbFData = new StringBuilder(GDefine.LEN_FDATA);

            int num = m_dtTestItem.Rows.Count;
            string m_sLastPortA = "", m_sLastPortB = "";
            clsTraceTest aTraceTest = new clsTraceTest();

            if (num == 0) return false;
            if (!m_IsVNADebug)
            {
                m_CInstrVNA.DisplayUpdate(true);//将仪表的显示功能打开
            }

            int i = 0;
            for (i = 0; i < num; i++)
            {
                if (m_bNeedQuit)
                    return false;

                #region 筛选测试项处理
                //获取换线次数
                int iChange = Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_Index].ToString().Trim());
                if (!m_productObj.enableConfig[i] || iChangeCount != iChange || !m_productObj.enableTestItem[i])
                {
                    if (i == num - 1)
                    {
                        if (aTraceTest.iTraceArrNum != 0)
                        { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                            //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                            int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB,
                                                              ref m_sCurReg, ref m_sLastReg,
                                                              ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                            if (iRetbefore == 2)
                                continue;
                            else if (iRetbefore == 0)
                                return false;
                            //if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                            //{
                            if (!TestTrace(aTraceTest, ref m_bTotalResult))
                            {
                                return false;
                            }
                            //}
                            //else
                            //{
                            //    if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                            //    {
                            //        return false;
                            //    }
                            //}

                        }
                    }
                    continue;
                }
                #endregion

                //this.Invoke(new EventHandler(ShowProcess));

                float Val;
                float Val2 = 0;
                int power = 10;

                #region 取值和预处理
                float InstrHigh = 999;
                float InstrLow = 999;
                clsTestItem arrTestItem = new clsTestItem();
                arrTestItem.iTestIndex = i;
                arrTestItem.sTestItem = m_dtTestItem.Rows[i][clsTestItem.chn_ItemName].ToString().Trim();
                arrTestItem.sTestName = m_dtTestItem.Rows[i][clsTestItem.chn_ParamName].ToString().Trim();
                arrTestItem.sFactSpec = m_dtTestItem.Rows[i][clsTestItem.chn_FactSpec].ToString().Trim();//内控要求 ≤1.43dB
                arrTestItem.sInstrCtrl = m_dtTestItem.Rows[i][clsTestItem.chn_InstrCtrl].ToString();//仪表特殊控制
                arrTestItem.sFreq = m_dtTestItem.Rows[i][clsTestItem.chn_Freq].ToString().Trim();//1830-1880MHz //Freq
                arrTestItem.sRandom = m_dtTestItem.Rows[i][clsTestItem.chn_TestNo].ToString().Trim();//角度索引
                arrTestItem.sTestFlag = m_dtTestItem.Rows[i][clsTestItem.chn_Done].ToString().Trim();
                arrTestItem.sPortA = m_dtTestItem.Rows[i][clsTestItem.chn_PortA].ToString().Trim();//GetStrPortAB(iTestCount, );//1端口连接 ANT1//并对应开关切换表获得端口号，以便调用校准文件
                arrTestItem.sPortB = m_dtTestItem.Rows[i][clsTestItem.chn_PortB].ToString().Trim();//GetStrPortAB(iTestCount, );//2端口连接 TXA1

                arrTestItem.sTestPortType = m_dtTestItem.Rows[i][clsTestItem.chn_PortType].ToString().Trim();//测试内容 S21//GetSParamStr(
                arrTestItem.sFormatType = m_dtTestItem.Rows[i][clsTestItem.chn_FormatType].ToString().Trim();//测试数据2 DISP_LOGM
                arrTestItem.sReport = m_dtTestItem.Rows[i][clsTestItem.chn_Report].ToString().Trim();//报表内容 最小值的绝对值
                arrTestItem.sBand = m_dtTestItem.Rows[i][clsTestItem.chn_Band].ToString().Trim();//校准带宽

                arrTestItem.iTestCount = iTestCount;
                arrTestItem.power = power;

                //RCU控制字段
                arrTestItem.sPortA_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString().Trim();
                arrTestItem.sPortB_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Angle].ToString().Trim();
                arrTestItem.sPortA_RCU = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString().Trim();
                arrTestItem.sPortB_RCU = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString().Trim();

                arrTestItem.sPortA_Tip = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Tip].ToString().Trim();
                arrTestItem.sPortB_Tip = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Tip].ToString().Trim();

                arrTestItem.sTestFunction = m_dtTestItem.Rows[i][clsTestItem.chn_TestFunction].ToString().Trim();

                //FAD
                arrTestItem.sMarkers = m_dtTestItem.Rows[i][clsTestItem.chn_sMarkers].ToString().Trim();
                arrTestItem.sAntennaType = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim());
                arrTestItem.sTestType = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sTestType].ToString().Trim());
                arrTestItem.sTestMethod = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sTestMethod].ToString().Trim());


                if (!GetFreqRange(arrTestItem.sFreq, ref arrTestItem.f1, ref arrTestItem.f2))
                {//频率拆分新方法
                    MessageBox.Show("频率范围" + arrTestItem.sFreq + "解析失败,请参考'420MHz-2010MHz' ");
                    return false;
                }

                #endregion

                #region RandomValue Items

                if (arrTestItem.sTestFlag != "True")
                {//对于不测试项，如果随机项有双引号则直接填写，否则进行随机取结果处理
                    if (arrTestItem.sRandom == "" || (arrTestItem.sRandom.IndexOf(",") == -1 && arrTestItem.sRandom.IndexOf('"') == -1))
                    {
                        MessageBox.Show("测试项 " + i + " 无效的取值范围: " + arrTestItem.sRandom + ",请参考: 80,105 ");
                        this.BeginInvoke(new EventHandler(ShowText), "\r\n " + i + " - " + "xxx 跳过无效测试项");
                        continue;
                    }

                    string strRandom = arrTestItem.sRandom;
                    string[] sContent = strRandom.Split('"');
                    if (sContent.Length == 3)
                    {//直接显示的内容，例如"pass"
                        clsInsertRow aInsertRow = new clsInsertRow();
                        aInsertRow.dgv = dgvTest;
                        aInsertRow.iRow = i;
                        aInsertRow.sValue = sContent[1];
                        aInsertRow.sResult = GDefine.ContentPass;

                        this.BeginInvoke(new EventHandler(FillTestValue), aInsertRow);
                    }
                    else
                    {
                        try
                        {
                            Regex reg = new Regex(@"-?(\d+)\.(\d+)|-?(\d+)");
                            MatchCollection ms0 = reg.Matches(strRandom);

                            float r1 = float.Parse(ms0[0].Value) * 100;
                            float r2 = float.Parse(ms0[1].Value) * 100;
                            //以时间为种子的短时间无法产生不重复随机，只能用guid  
                            Random randomVal = new Random(Guid.NewGuid().GetHashCode());
                            if (r1 < r2)
                                Val = randomVal.Next((int)r1, (int)r2) / 100f;
                            else
                                Val = randomVal.Next((int)r2, (int)r1) / 100f;
                            ValResult vr0 = new ValResult();
                            vr0.Val = Val;
                            vr0.No = i + 1;
                            vr0.sResult = GDefine.ContentPass;
                            vr0.Val2 = Val2;

                            if (ms0.Count == 4)
                            {
                                r1 = float.Parse(ms0[2].Value) * 100;
                                r2 = float.Parse(ms0[3].Value) * 100;
                                if (r1 < r2)
                                    Val = randomVal.Next((int)r1, (int)r2) / 100f;
                                else
                                    Val = randomVal.Next((int)r2, (int)r1) / 100f;
                                vr0.Val2 = Val;
                            }

                            clsInsertRow aInsertRow = new clsInsertRow();
                            aInsertRow.dgv = dgvTest;
                            aInsertRow.iRow = i;
                            aInsertRow.sValue = vr0.Val.ToString();
                            aInsertRow.sResult = vr0.sResult;

                            this.BeginInvoke(new EventHandler(FillTestValue), aInsertRow);
                            //FillTestValue(i, vr0.Val.ToString(), vr0.sResult);
                        }
                        catch (Exception ex)
                        {
                            //Insert_Standard_ErrorLog.Insert("LoadConfig", "LoadConfig Error --> " + ex.Message);
                            MessageBox.Show("ContTest err Random" + ex.Message);
                        }
                    }

                    continue;
                }

                #endregion

                #region 非本次换线对应的测试项
                if (/* m_Instr.Switch_Type != (int)SwitchType.SWITCH_NONE && */arrTestItem.sRandom != arrTestItem.iTestCount.ToString())
                {//如果是自动切换则跳过一些非本次换线对应的测试项
                    if (aTraceTest.iTraceArrNum != 0)
                    { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                        //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                        int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB,
                                                          ref m_sCurReg, ref m_sLastReg,
                                                          ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                        if (iRetbefore == 2)
                            continue;
                        else if (iRetbefore == 0)
                            return false;

                        //if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                        //{
                        if (!TestTrace(aTraceTest, ref m_bTotalResult))
                        {
                            return false;
                        }
                        //}
                        //else
                        //{
                        //    if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                        //    {
                        //        return false;
                        //    }
                        //}
                    }
                    continue;
                }
                #endregion

                //取值模式，GetValueMode 
                //一种，GetValueMode = 0;测试模式0时，根据频率设置起止频段，然后取这一段的最优点，
                //二种，GetValueMode = 1;测试模式1时，根据 当前的BAND，如果是类似于 0-8500 则用segment取值，
                //三种，GetValueMode = 2;测试模式1时，根据 当前的BAND，如果是类似于 1830-1880 则集中trace取值,包括单点取值
                //四种，GetValueMode = 4;测试模式1时，

                if (m_cProject.sNewTestMode == "1" || m_cProject.sNewTestMode == "2")
                {//新的测试模式1时
                    if (arrTestItem.sBand.Trim() == "")
                    {//
                        this.BeginInvoke(new EventHandler(ShowText), "必测项" + i + " 未输入校准频段\r\n");
                        continue;
                    }

                    if (arrTestItem.sBand[0] == '0' && arrTestItem.sBand[1] == '-')
                    {//如果是全频段测试，从segment table 中取点数

                        #region 全频段segment测试
                        //int iPointStart = 0, iPointEnd = 0;
                        //if (aTraceTest.iTraceArrNum != 0)
                        //{ //把之前累计的trace进行一次统一处理
                        //    //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                        //    int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                        //                                                 aTraceTest.arrTestItem[0]);
                        //    if (iRetbefore == 2)
                        //        continue;
                        //    else if (iRetbefore == 0)
                        //        return false;
                        //    TestTrace(aTraceTest, ref m_bTotalResult);
                        //}
                        ////再处理segment
                        ////测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                        //int iRetnow = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                        //                                                 arrTestItem);
                        //if (iRetnow == 2)
                        //    continue;
                        //else if (iRetnow == 0)
                        //    return false;
                        //iGetValueMode = 1;
                        ////需要根据频率，获取对应segment表中的点数对应的值

                        //if (!GetPointFromSegment(dsSegment.Tables[0], arrTestItem.sFreq, ref iPointStart, ref iPointEnd))
                        //{
                        //    this.BeginInvoke(new EventHandler(ShowText), "Segment表取点失败，请检查格式!\r\n");
                        //    return false; ;
                        //}
                        //NewTestMode(ref sbFData, ref fArray, iPointStart, iPointEnd - iPointStart + 1, iGetValueMode, bSameCalFileTest,
                        //    arrTestItem.sFormatType, arrTestItem.sTestPortType, arrTestItem.f1, arrTestItem.f2,
                        //    ref InstrLow, ref InstrHigh);
                        #endregion

                    }
                    else
                    {//否则直接去trace中的值,增加智能判断模式，统一保存到数组，当遇到非trace时从数组取出，统一打trace取值。

                        #region trace测试

                        iGetValueMode = 2;
                        if (aTraceTest.iTraceArrNum == 0)
                        {//新的trace测试
                            aTraceTest.sBand = arrTestItem.sBand;
                            aTraceTest.sPortA = arrTestItem.sPortA;
                            aTraceTest.sPortB = arrTestItem.sPortB;
                            aTraceTest.f1 = arrTestItem.f1;////要求同时测试的trace必须是同一个频率段
                            aTraceTest.f2 = arrTestItem.f2;
                            aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                            aTraceTest.iTraceArrNum++;

                            //RCU控制字段
                            aTraceTest.sPortA_Angle = arrTestItem.sPortA_Angle;
                            aTraceTest.sPortB_Angle = arrTestItem.sPortB_Angle;
                            aTraceTest.sPortA_RCU = arrTestItem.sPortA_RCU;
                            aTraceTest.sPortB_RCU = arrTestItem.sPortB_RCU;
                            aTraceTest.sTestFunction = arrTestItem.sTestFunction;
                        }
                        else
                        {
                            if (aTraceTest.sBand == arrTestItem.sBand &&
                                aTraceTest.sPortA == arrTestItem.sPortA &&
                                aTraceTest.sPortB == arrTestItem.sPortB &&
                                aTraceTest.f1 == arrTestItem.f1 &&
                                aTraceTest.f2 == arrTestItem.f2 &&
                                //判断RCU字段
                                aTraceTest.sPortA_Angle == arrTestItem.sPortA_Angle &&
                                aTraceTest.sPortB_Angle == arrTestItem.sPortB_Angle &&
                                aTraceTest.sPortA_RCU == arrTestItem.sPortA_RCU &&
                                aTraceTest.sPortB_RCU == arrTestItem.sPortB_RCU &&
                                aTraceTest.sTestFunction == arrTestItem.sTestFunction)
                            {//存起来一起处理
                                aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                                aTraceTest.iTraceArrNum++;
                            }
                            else
                            {//端口改变或带宽改变，则进行一次统一处理，并重新存储
                                //进行一次统一处理
                                //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                                int iRet = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                                             aTraceTest.arrTestItem[0]);
                                if (iRet == 2)
                                    continue;
                                else if (iRet == 0)
                                    return false;

                                //将存储的trace一并测试
                                //if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                                //{
                                if (!TestTrace(aTraceTest, ref m_bTotalResult))
                                {
                                    return false;
                                }
                                //}
                                //else
                                //{
                                //    if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                                //    {
                                //        return false;
                                //    }
                                //}

                                //并重新存储
                                aTraceTest.iTraceArrNum = 0;
                                aTraceTest.sBand = arrTestItem.sBand;
                                aTraceTest.sPortA = arrTestItem.sPortA;
                                aTraceTest.sPortB = arrTestItem.sPortB;
                                aTraceTest.f1 = arrTestItem.f1;////要求同时测试的trace必须是同一个频率段
                                aTraceTest.f2 = arrTestItem.f2;
                                aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                                aTraceTest.iTraceArrNum++;
                                //并重新存储RCU控制字段
                                aTraceTest.sPortA_Angle = arrTestItem.sPortA_Angle;
                                aTraceTest.sPortB_Angle = arrTestItem.sPortB_Angle;
                                aTraceTest.sPortA_RCU = arrTestItem.sPortA_RCU;
                                aTraceTest.sPortB_RCU = arrTestItem.sPortB_RCU;
                                aTraceTest.sTestFunction = arrTestItem.sTestFunction;
                            }
                        }

                        if (i == num - 1 && aTraceTest.iTraceArrNum != 0)
                        { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                            //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                            int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg,
                                                              ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                            if (iRetbefore == 2)
                                continue;
                            else if (iRetbefore == 0)
                                return false;

                            //if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                            //{
                            if (!TestTrace(aTraceTest, ref m_bTotalResult))
                            {
                                return false;
                            }
                            //}
                            //else
                            //{
                            //    if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                            //    {
                            //        return false;
                            //    }
                            //}

                        }

                        continue;

                        #endregion

                    }
                }

                if (arrTestItem.sFormatType == "DISP_DELA")
                {
                    InstrLow = InstrLow * (float)Math.Pow(10, 9);
                    InstrHigh = InstrHigh * (float)Math.Pow(10, 9);
                }
                this.BeginInvoke(new EventHandler(ShowText), "ROW_" + i + ": InsLo=" + InstrLow + ", InsHi=" + InstrHigh + "\r\n");

                DealResult(arrTestItem, InstrLow, InstrHigh, ref m_bTotalResult);
            }

            return true;
        }

        bool ContTestNew(int iTestNo, int iChangeIndex)
        {
            if (m_dtTestItem.Rows.Count == 0) return false;
            List<List<clsTestItem>> lstAllTestItem = new List<List<clsTestItem>>();
            for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
            {
                if (m_bNeedQuit) return false;
                #region 筛选项处理
                if (!m_productObj.enableConfig[i] || !m_productObj.enableTestItem[i]) continue;
                int iIndex = Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_Index].ToString().Trim());//组索引-端口
                int iNo = Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_TestNo].ToString().Trim());//索引-角度
                if (iChangeIndex != iIndex || iTestNo != iNo) continue;
                #endregion

                #region 取值和预处理
                string pa = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString();
                string PortA_RCU = pa;//.Substring(0, pa.Length - GDefine.RCU_PORT_NAME.Length);
                string pb = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString();
                string PortB_RCU = pb;//.Substring(0, pb.Length - GDefine.RCU_PORT_NAME.Length);

                clsTestItem TestItem = new clsTestItem();
                TestItem.iTestIndex = i;
                TestItem.sTestItem = m_dtTestItem.Rows[i][clsTestItem.chn_ItemName].ToString().Trim();
                TestItem.sTestName = m_dtTestItem.Rows[i][clsTestItem.chn_ParamName].ToString().Trim();
                TestItem.sFactSpec = m_dtTestItem.Rows[i][clsTestItem.chn_FactSpec].ToString().Trim();//内控要求 ≤1.43dB
                TestItem.sInstrCtrl = m_dtTestItem.Rows[i][clsTestItem.chn_InstrCtrl].ToString();//仪表特殊控制
                TestItem.sFreq = m_dtTestItem.Rows[i][clsTestItem.chn_Freq].ToString().Trim();//1830-1880MHz //Freq
                TestItem.sRandom = m_dtTestItem.Rows[i][clsTestItem.chn_TestNo].ToString().Trim();//角度索引
                TestItem.sTestFlag = m_dtTestItem.Rows[i][clsTestItem.chn_Done].ToString().Trim();
                TestItem.sPortA = m_dtTestItem.Rows[i][clsTestItem.chn_PortA].ToString().Trim();//GetStrPortAB(iTestCount, );//1端口连接 ANT1//并对应开关切换表获得端口号，以便调用校准文件
                TestItem.sPortB = m_dtTestItem.Rows[i][clsTestItem.chn_PortB].ToString().Trim();//GetStrPortAB(iTestCount, );//2端口连接 TXA1
                TestItem.sTestPortType = m_dtTestItem.Rows[i][clsTestItem.chn_PortType].ToString().Trim();//测试内容 S21//GetSParamStr(
                TestItem.sFormatType = m_dtTestItem.Rows[i][clsTestItem.chn_FormatType].ToString().Trim();//测试数据2 DISP_LOGM
                TestItem.sReport = m_dtTestItem.Rows[i][clsTestItem.chn_Report].ToString().Trim();//报表内容 最小值的绝对值
                TestItem.sBand = m_dtTestItem.Rows[i][clsTestItem.chn_Band].ToString().Trim();//校准带宽
                TestItem.iTestCount = iTestNo;
                TestItem.power = 10;
                //RCU控制字段
                TestItem.sPortA_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString().Trim();
                TestItem.sPortB_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Angle].ToString().Trim();
                TestItem.sPortA_RCU = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString().Trim();
                TestItem.sPortB_RCU = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString().Trim();
                TestItem.sPortA_Tip = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Tip].ToString().Trim();
                TestItem.sPortB_Tip = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Tip].ToString().Trim();
                TestItem.sTestFunction = m_dtTestItem.Rows[i][clsTestItem.chn_TestFunction].ToString().Trim();
                //FAD
                TestItem.sMarkers = m_dtTestItem.Rows[i][clsTestItem.chn_sMarkers].ToString().Trim();
                TestItem.sAntennaType = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim());
                TestItem.sTestType = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sTestType].ToString().Trim());
                TestItem.sTestMethod = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sTestMethod].ToString().Trim());


                if (!GetFreqRange(TestItem.sFreq, ref TestItem.f1, ref TestItem.f2))
                {
                    MessageBox.Show("频率范围" + TestItem.sFreq + "解析失败,请参考'420MHz-2010MHz' ");
                    return false;
                }
                #endregion

                #region 合并取出测试项
                if (lstAllTestItem.Count == 0)
                {
                    List<clsTestItem> lstTestItem = new List<clsTestItem>();
                    lstTestItem.Add(TestItem);
                    lstAllTestItem.Add(lstTestItem);
                }
                else
                {
                    List<clsTestItem> lstNewItem = new List<clsTestItem>();
                    lstNewItem.Add(TestItem);
                    //3.5 linq,lambda==>lstTestItem.Where(p => p.sPortA_RCU == PortA_RCU && p.sPortB_RCU == PortB_RCU).Count();
                    //2.0 delegate
                    if (lstAllTestItem.Exists(delegate(List<clsTestItem> lstItem)
                     {//foreach until return true
                         if (lstItem.Exists(delegate(clsTestItem item)
                         {
                             if (item.sPortA_RCU == PortA_RCU && item.sPortB_RCU == PortB_RCU)
                             {
                                 return true;
                             }
                             else
                             {
                                 return false;
                             }
                         }))
                         {
                             lstItem.Add(TestItem);
                             return true;
                         }
                         else
                         {
                             return false;
                         }
                     }))
                    {

                    }
                    else
                    {
                        lstAllTestItem.Add(lstNewItem);
                    }
                }
                #endregion
            }

            m_CInstrVNA.DisplayUpdate(true);
            string m_sLastPortA = "", m_sLastPortB = "";
            bool bSameCalFileTest = false;//相同的校准文件统一读值标志           
            for (int i = 0; i < lstAllTestItem.Count; i++)
            {

                if (m_bNeedQuit) return false;
                int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest, lstAllTestItem[i][0]);
                if (iRetbefore == 2)
                    continue;
                else if (iRetbefore == 0)
                    return false;
                if (!TestTrace(lstAllTestItem[i], ref m_bTotalResult))
                {
                    return false;
                }
            }
            return true;
        }
        bool ContTestTD(int iTestCount, int iChangeCount, List<string> lstTestPortAB)
        {//如果iTestCount = 0表示手动换线，1表示第一次换线，2表示第二次换线，以此类推          
            m_arrTrace_temp.Clear(); vanLastSet = new clsVNASetting();
            int iGetValueMode = 0;//取值模式
            //bool bSegmentTestMode = false;//从Segment table 中取值标志
            bool bSameCalFileTest = false;//相同的校准文件统一读值标志
            StringBuilder sbFData = new StringBuilder(GDefine.LEN_FDATA);

            int num = m_dtTestItem.Rows.Count;
            string m_sLastPortA = "", m_sLastPortB = "";
            clsTraceTest aTraceTest = new clsTraceTest();

            if (num == 0) return false;
            if (!m_IsVNADebug)
            {
                m_CInstrVNA.DisplayUpdate(true);//将仪表的显示功能打开
            }

            if (lstTestPortAB.Count > 0)
            {
                for (int kk = 0; kk < lstTestPortAB.Count; kk++)
                {
                    #region  for num
                    int i = 0;
                    for (i = 0; i < num; i++)
                    {
                        if (m_bNeedQuit)
                            return false;
                        string PortAB = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString() + ";" + m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString();
                        if (PortAB != lstTestPortAB[kk]) continue;
                        //if (PortAB == "FA-P4;D-P4")
                        //{
                        //    break;
                        //}

                        #region 筛选测试项处理
                        //获取换线次数
                        int iChange = Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_Index].ToString().Trim());
                        string aglIndex = m_dtTestItem.Rows[i][clsTestItem.chn_TestNo].ToString().Trim();
                        if (!m_productObj.enableConfig[i] || iChangeCount != iChange || !m_productObj.enableTestItem[i] || aglIndex != iTestCount.ToString())
                        {

                            //if (i == num - 1)
                            //{
                            //    if (aTraceTest.iTraceArrNum != 0)
                            //    { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                            //        //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                            //        int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB,
                            //                                          ref m_sCurReg, ref m_sLastReg,
                            //                                          ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                            //        if (iRetbefore == 2)
                            //            continue;
                            //        else if (iRetbefore == 0)
                            //            return false;
                            //        if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                            //        {
                            //            if (!TestTrace(aTraceTest, ref m_bTotalResult))
                            //            {
                            //                return false;
                            //            }
                            //        }
                            //        else
                            //        {
                            //            if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                            //            {
                            //                return false;
                            //            }
                            //        }

                            //    }
                            //}
                            continue;
                        }
                        #endregion

                        //this.Invoke(new EventHandler(ShowProcess));

                        float Val;
                        float Val2 = 0;
                        int power = 10;

                        #region 取值和预处理
                        float InstrHigh = 999;
                        float InstrLow = 999;
                        clsTestItem arrTestItem = new clsTestItem();
                        arrTestItem.iTestIndex = i;
                        arrTestItem.sTestItem = m_dtTestItem.Rows[i][clsTestItem.chn_ItemName].ToString().Trim();
                        arrTestItem.sTestName = m_dtTestItem.Rows[i][clsTestItem.chn_ParamName].ToString().Trim();
                        arrTestItem.sFactSpec = m_dtTestItem.Rows[i][clsTestItem.chn_FactSpec].ToString().Trim();//内控要求 ≤1.43dB
                        arrTestItem.sInstrCtrl = m_dtTestItem.Rows[i][clsTestItem.chn_InstrCtrl].ToString();//仪表特殊控制
                        arrTestItem.sFreq = m_dtTestItem.Rows[i][clsTestItem.chn_Freq].ToString().Trim();//1830-1880MHz //Freq
                        arrTestItem.sRandom = m_dtTestItem.Rows[i][clsTestItem.chn_TestNo].ToString().Trim();//角度索引
                        arrTestItem.sTestFlag = m_dtTestItem.Rows[i][clsTestItem.chn_Done].ToString().Trim();
                        arrTestItem.sPortA = m_dtTestItem.Rows[i][clsTestItem.chn_PortA].ToString().Trim();//GetStrPortAB(iTestCount, );//1端口连接 ANT1//并对应开关切换表获得端口号，以便调用校准文件
                        arrTestItem.sPortB = m_dtTestItem.Rows[i][clsTestItem.chn_PortB].ToString().Trim();//GetStrPortAB(iTestCount, );//2端口连接 TXA1

                        arrTestItem.sTestPortType = m_dtTestItem.Rows[i][clsTestItem.chn_PortType].ToString().Trim();//测试内容 S21//GetSParamStr(
                        arrTestItem.sFormatType = m_dtTestItem.Rows[i][clsTestItem.chn_FormatType].ToString().Trim();//测试数据2 DISP_LOGM
                        arrTestItem.sReport = m_dtTestItem.Rows[i][clsTestItem.chn_Report].ToString().Trim();//报表内容 最小值的绝对值
                        arrTestItem.sBand = m_dtTestItem.Rows[i][clsTestItem.chn_Band].ToString().Trim();//校准带宽

                        arrTestItem.iTestCount = iTestCount;//角度索引
                        arrTestItem.power = power;

                        //RCU控制字段
                        arrTestItem.sPortA_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString().Trim();
                        arrTestItem.sPortB_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Angle].ToString().Trim();
                        arrTestItem.sPortA_RCU = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString().Trim();
                        arrTestItem.sPortB_RCU = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString().Trim();

                        arrTestItem.sPortA_Tip = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Tip].ToString().Trim();
                        arrTestItem.sPortB_Tip = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Tip].ToString().Trim();

                        arrTestItem.sTestFunction = m_dtTestItem.Rows[i][clsTestItem.chn_TestFunction].ToString().Trim();

                        //FAD
                        arrTestItem.sMarkers = m_dtTestItem.Rows[i][clsTestItem.chn_sMarkers].ToString().Trim();
                        arrTestItem.sAntennaType = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim());
                        arrTestItem.sTestType = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sTestType].ToString().Trim());
                        arrTestItem.sTestMethod = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sTestMethod].ToString().Trim());


                        if (!GetFreqRange(arrTestItem.sFreq, ref arrTestItem.f1, ref arrTestItem.f2))
                        {//频率拆分新方法
                            MessageBox.Show("频率范围" + arrTestItem.sFreq + "解析失败,请参考'420MHz-2010MHz' ");
                            return false;
                        }

                        #endregion

                        #region RandomValue Items
                        //if (arrTestItem.sTestFlag != "True")
                        //{//对于不测试项，如果随机项有双引号则直接填写，否则进行随机取结果处理
                        //    if (arrTestItem.sRandom == "" || (arrTestItem.sRandom.IndexOf(",") == -1 && arrTestItem.sRandom.IndexOf('"') == -1))
                        //    {
                        //        MessageBox.Show("测试项 " + i + " 无效的取值范围: " + arrTestItem.sRandom + ",请参考: 80,105 ");
                        //        this.BeginInvoke(new EventHandler(ShowText), "\r\n " + i + " - " + "xxx 跳过无效测试项");
                        //        continue;
                        //    }

                        //    string strRandom = arrTestItem.sRandom;
                        //    string[] sContent = strRandom.Split('"');
                        //    if (sContent.Length == 3)
                        //    {//直接显示的内容，例如"pass"
                        //        clsInsertRow aInsertRow = new clsInsertRow();
                        //        aInsertRow.dgv = dgvTest;
                        //        aInsertRow.iRow = i;
                        //        aInsertRow.sValue = sContent[1];
                        //        aInsertRow.sResult = GDefine.ContentPass;

                        //        this.BeginInvoke(new EventHandler(FillTestValue), aInsertRow);
                        //    }
                        //    else
                        //    {
                        //        try
                        //        {
                        //            Regex reg = new Regex(@"-?(\d+)\.(\d+)|-?(\d+)");
                        //            MatchCollection ms0 = reg.Matches(strRandom);

                        //            float r1 = float.Parse(ms0[0].Value) * 100;
                        //            float r2 = float.Parse(ms0[1].Value) * 100;
                        //            //以时间为种子的短时间无法产生不重复随机，只能用guid  
                        //            Random randomVal = new Random(Guid.NewGuid().GetHashCode());
                        //            if (r1 < r2)
                        //                Val = randomVal.Next((int)r1, (int)r2) / 100f;
                        //            else
                        //                Val = randomVal.Next((int)r2, (int)r1) / 100f;
                        //            ValResult vr0 = new ValResult();
                        //            vr0.Val = Val;
                        //            vr0.No = i + 1;
                        //            vr0.sResult = GDefine.ContentPass;
                        //            vr0.Val2 = Val2;

                        //            if (ms0.Count == 4)
                        //            {
                        //                r1 = float.Parse(ms0[2].Value) * 100;
                        //                r2 = float.Parse(ms0[3].Value) * 100;
                        //                if (r1 < r2)
                        //                    Val = randomVal.Next((int)r1, (int)r2) / 100f;
                        //                else
                        //                    Val = randomVal.Next((int)r2, (int)r1) / 100f;
                        //                vr0.Val2 = Val;
                        //            }

                        //            clsInsertRow aInsertRow = new clsInsertRow();
                        //            aInsertRow.dgv = dgvTest;
                        //            aInsertRow.iRow = i;
                        //            aInsertRow.sValue = vr0.Val.ToString();
                        //            aInsertRow.sResult = vr0.sResult;

                        //            this.BeginInvoke(new EventHandler(FillTestValue), aInsertRow);
                        //            //FillTestValue(i, vr0.Val.ToString(), vr0.sResult);
                        //        }
                        //        catch (Exception ex)
                        //        {
                        //            //Insert_Standard_ErrorLog.Insert("LoadConfig", "LoadConfig Error --> " + ex.Message);
                        //            MessageBox.Show("ContTest err Random" + ex.Message);
                        //        }
                        //    }

                        //    continue;
                        //}
                        #endregion

                        #region 非本次换线对应的测试项
                        //if (/* m_Instr.Switch_Type != (int)SwitchType.SWITCH_NONE && */arrTestItem.sRandom != arrTestItem.iTestCount.ToString())
                        //{//如果是自动切换则跳过一些非本次换线对应的测试项
                        //    if (aTraceTest.iTraceArrNum != 0)
                        //    { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                        //        //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                        //        int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB,
                        //                                          ref m_sCurReg, ref m_sLastReg,
                        //                                          ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                        //        if (iRetbefore == 2)
                        //            continue;
                        //        else if (iRetbefore == 0)
                        //            return false;

                        //        if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                        //        {
                        //            if (!TestTrace(aTraceTest, ref m_bTotalResult))
                        //            {
                        //                return false;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                        //            {
                        //                return false;
                        //            }
                        //        }
                        //    }
                        //    continue;
                        //}
                        #endregion

                        //取值模式，GetValueMode 
                        //一种，GetValueMode = 0;测试模式0时，根据频率设置起止频段，然后取这一段的最优点，
                        //二种，GetValueMode = 1;测试模式1时，根据 当前的BAND，如果是类似于 0-8500 则用segment取值，
                        //三种，GetValueMode = 2;测试模式1时，根据 当前的BAND，如果是类似于 1830-1880 则集中trace取值,包括单点取值
                        //四种，GetValueMode = 4;测试模式1时，

                        if (m_cProject.sNewTestMode == "1" || m_cProject.sNewTestMode == "2")
                        {//新的测试模式1时
                            if (arrTestItem.sBand.Trim() == "")
                            {//
                                this.BeginInvoke(new EventHandler(ShowText), "必测项" + i + " 未输入校准频段\r\n");
                                continue;
                            }

                            if (arrTestItem.sBand[0] == '0' && arrTestItem.sBand[1] == '-')
                            {//如果是全频段测试，从segment table 中取点数

                                #region 全频段segment测试
                                //int iPointStart = 0, iPointEnd = 0;
                                //if (aTraceTest.iTraceArrNum != 0)
                                //{ //把之前累计的trace进行一次统一处理
                                //    //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                                //    int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                                //                                                 aTraceTest.arrTestItem[0]);
                                //    if (iRetbefore == 2)
                                //        continue;
                                //    else if (iRetbefore == 0)
                                //        return false;
                                //    TestTrace(aTraceTest, ref m_bTotalResult);
                                //}
                                ////再处理segment
                                ////测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                                //int iRetnow = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                                //                                                 arrTestItem);
                                //if (iRetnow == 2)
                                //    continue;
                                //else if (iRetnow == 0)
                                //    return false;
                                //iGetValueMode = 1;
                                ////需要根据频率，获取对应segment表中的点数对应的值

                                //if (!GetPointFromSegment(dsSegment.Tables[0], arrTestItem.sFreq, ref iPointStart, ref iPointEnd))
                                //{
                                //    this.BeginInvoke(new EventHandler(ShowText), "Segment表取点失败，请检查格式!\r\n");
                                //    return false; ;
                                //}
                                //NewTestMode(ref sbFData, ref fArray, iPointStart, iPointEnd - iPointStart + 1, iGetValueMode, bSameCalFileTest,
                                //    arrTestItem.sFormatType, arrTestItem.sTestPortType, arrTestItem.f1, arrTestItem.f2,
                                //    ref InstrLow, ref InstrHigh);
                                #endregion

                            }
                            else
                            {//否则直接去trace中的值,增加智能判断模式，统一保存到数组，当遇到非trace时从数组取出，统一打trace取值。

                                #region trace测试

                                iGetValueMode = 2;
                                if (aTraceTest.iTraceArrNum == 0)
                                {//新的trace测试
                                    aTraceTest.sTestItem = arrTestItem.sTestItem;
                                    aTraceTest.sFormatType = arrTestItem.sFormatType;
                                    aTraceTest.sTestPortType = arrTestItem.sTestPortType;

                                    aTraceTest.sBand = arrTestItem.sBand;
                                    aTraceTest.sPortA = arrTestItem.sPortA;
                                    aTraceTest.sPortB = arrTestItem.sPortB;
                                    aTraceTest.f1 = arrTestItem.f1;////要求同时测试的trace必须是同一个频率段
                                    aTraceTest.f2 = arrTestItem.f2;
                                    aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                                    aTraceTest.iTraceArrNum++;

                                    //RCU控制字段
                                    aTraceTest.sPortA_Angle = arrTestItem.sPortA_Angle;
                                    aTraceTest.sPortB_Angle = arrTestItem.sPortB_Angle;
                                    aTraceTest.sPortA_RCU = arrTestItem.sPortA_RCU;
                                    aTraceTest.sPortB_RCU = arrTestItem.sPortB_RCU;
                                    aTraceTest.sTestFunction = arrTestItem.sTestFunction;
                                }
                                //else
                                //{
                                //    if (aTraceTest.sTestName == arrTestItem.sTestName &&
                                //        aTraceTest.sFormatType == arrTestItem.sFormatType &&
                                //        aTraceTest.sTestPortType == arrTestItem.sTestPortType &&

                                //        aTraceTest.sBand == arrTestItem.sBand &&
                                //        aTraceTest.sPortA == arrTestItem.sPortA &&
                                //        aTraceTest.sPortB == arrTestItem.sPortB &&
                                //        aTraceTest.f1 == arrTestItem.f1 &&
                                //        aTraceTest.f2 == arrTestItem.f2 &&
                                //        //判断RCU字段
                                //        aTraceTest.sPortA_Angle == arrTestItem.sPortA_Angle &&
                                //        aTraceTest.sPortB_Angle == arrTestItem.sPortB_Angle &&
                                //        aTraceTest.sPortA_RCU == arrTestItem.sPortA_RCU &&
                                //        aTraceTest.sPortB_RCU == arrTestItem.sPortB_RCU &&
                                //        aTraceTest.sTestFunction == arrTestItem.sTestFunction)
                                //    {//存起来一起处理
                                //        aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                                //        aTraceTest.iTraceArrNum++;
                                //    }
                                //    else
                                //    {//端口改变或带宽改变，则进行一次统一处理，并重新存储
                                //        //进行一次统一处理
                                //        //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                                //        int iRet = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                                //                     aTraceTest.arrTestItem[0]);
                                //        if (iRet == 2)
                                //            continue;
                                //        else if (iRet == 0)
                                //            return false;

                                //        //将存储的trace一并测试
                                //        if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                                //        {
                                //            if (!TestTrace(aTraceTest, ref m_bTotalResult))
                                //            {
                                //                return false;
                                //            }
                                //        }
                                //        else
                                //        {
                                //            if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                                //            {
                                //                return false;
                                //            }
                                //        }

                                //        //并重新存储
                                //        aTraceTest.iTraceArrNum = 0;
                                //        aTraceTest.sBand = arrTestItem.sBand;
                                //        aTraceTest.sPortA = arrTestItem.sPortA;
                                //        aTraceTest.sPortB = arrTestItem.sPortB;
                                //        aTraceTest.f1 = arrTestItem.f1;////要求同时测试的trace必须是同一个频率段
                                //        aTraceTest.f2 = arrTestItem.f2;
                                //        aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                                //        aTraceTest.iTraceArrNum++;
                                //        //并重新存储RCU控制字段
                                //        aTraceTest.sPortA_Angle = arrTestItem.sPortA_Angle;
                                //        aTraceTest.sPortB_Angle = arrTestItem.sPortB_Angle;
                                //        aTraceTest.sPortA_RCU = arrTestItem.sPortA_RCU;
                                //        aTraceTest.sPortB_RCU = arrTestItem.sPortB_RCU;
                                //        aTraceTest.sTestFunction = arrTestItem.sTestFunction;
                                //    }
                                //}

                                if (/*i == num - 1 &&*/ aTraceTest.iTraceArrNum != 0)
                                { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                                    //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                                    int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg,
                                                                      ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                                    if (iRetbefore == 2)
                                        return false;// continue;
                                    else if (iRetbefore == 0)
                                        return false;


                                    if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                                    {
                                        return false;
                                    }

                                }
                                aTraceTest.iTraceArrNum = 0;
                                continue;

                                #endregion

                            }
                        }

                        if (arrTestItem.sFormatType == "DISP_DELA")
                        {
                            InstrLow = InstrLow * (float)Math.Pow(10, 9);
                            InstrHigh = InstrHigh * (float)Math.Pow(10, 9);
                        }
                        this.BeginInvoke(new EventHandler(ShowText), "ROW_" + i + ": InsLo=" + InstrLow + ", InsHi=" + InstrHigh + "\r\n");

                        DealResult(arrTestItem, InstrLow, InstrHigh, ref m_bTotalResult);
                    }
                    #endregion
                }
            }
            else
            {
                #region  for num
                int i = 0;
                for (i = 0; i < num; i++)
                {
                    if (m_bNeedQuit)
                        return false;
                    string PortAB = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString() + ";" + m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString();
                    //if (PortAB != lstTestPortAB[kk]) continue;
                    //if (PortAB == "FA-P4;D-P4")
                    //{
                    //    break;
                    //}

                    #region 筛选测试项处理
                    //获取换线次数
                    int iChange = Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_Index].ToString().Trim());
                    string aglIndex = m_dtTestItem.Rows[i][clsTestItem.chn_TestNo].ToString().Trim();
                    if (!m_productObj.enableConfig[i] || iChangeCount != iChange || !m_productObj.enableTestItem[i] || aglIndex != iTestCount.ToString())
                    {

                        //if (i == num - 1)
                        //{
                        //    if (aTraceTest.iTraceArrNum != 0)
                        //    { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                        //        //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                        //        int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB,
                        //                                          ref m_sCurReg, ref m_sLastReg,
                        //                                          ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                        //        if (iRetbefore == 2)
                        //            continue;
                        //        else if (iRetbefore == 0)
                        //            return false;
                        //        if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                        //        {
                        //            if (!TestTrace(aTraceTest, ref m_bTotalResult))
                        //            {
                        //                return false;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                        //            {
                        //                return false;
                        //            }
                        //        }

                        //    }
                        //}
                        continue;
                    }
                    #endregion

                    //this.Invoke(new EventHandler(ShowProcess));

                    float Val;
                    float Val2 = 0;
                    int power = 10;

                    #region 取值和预处理
                    float InstrHigh = 999;
                    float InstrLow = 999;
                    clsTestItem arrTestItem = new clsTestItem();
                    arrTestItem.iTestIndex = i;
                    arrTestItem.sTestItem = m_dtTestItem.Rows[i][clsTestItem.chn_ItemName].ToString().Trim();
                    arrTestItem.sTestName = m_dtTestItem.Rows[i][clsTestItem.chn_ParamName].ToString().Trim();
                    arrTestItem.sFactSpec = m_dtTestItem.Rows[i][clsTestItem.chn_FactSpec].ToString().Trim();//内控要求 ≤1.43dB
                    arrTestItem.sInstrCtrl = m_dtTestItem.Rows[i][clsTestItem.chn_InstrCtrl].ToString();//仪表特殊控制
                    arrTestItem.sFreq = m_dtTestItem.Rows[i][clsTestItem.chn_Freq].ToString().Trim();//1830-1880MHz //Freq
                    arrTestItem.sRandom = m_dtTestItem.Rows[i][clsTestItem.chn_TestNo].ToString().Trim();//角度索引
                    arrTestItem.sTestFlag = m_dtTestItem.Rows[i][clsTestItem.chn_Done].ToString().Trim();
                    arrTestItem.sPortA = m_dtTestItem.Rows[i][clsTestItem.chn_PortA].ToString().Trim();//GetStrPortAB(iTestCount, );//1端口连接 ANT1//并对应开关切换表获得端口号，以便调用校准文件
                    arrTestItem.sPortB = m_dtTestItem.Rows[i][clsTestItem.chn_PortB].ToString().Trim();//GetStrPortAB(iTestCount, );//2端口连接 TXA1

                    arrTestItem.sTestPortType = m_dtTestItem.Rows[i][clsTestItem.chn_PortType].ToString().Trim();//测试内容 S21//GetSParamStr(
                    arrTestItem.sFormatType = m_dtTestItem.Rows[i][clsTestItem.chn_FormatType].ToString().Trim();//测试数据2 DISP_LOGM
                    arrTestItem.sReport = m_dtTestItem.Rows[i][clsTestItem.chn_Report].ToString().Trim();//报表内容 最小值的绝对值
                    arrTestItem.sBand = m_dtTestItem.Rows[i][clsTestItem.chn_Band].ToString().Trim();//校准带宽

                    arrTestItem.iTestCount = iTestCount;//角度索引
                    arrTestItem.power = power;

                    //RCU控制字段
                    arrTestItem.sPortA_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString().Trim();
                    arrTestItem.sPortB_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Angle].ToString().Trim();
                    arrTestItem.sPortA_RCU = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString().Trim();
                    arrTestItem.sPortB_RCU = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString().Trim();

                    arrTestItem.sPortA_Tip = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Tip].ToString().Trim();
                    arrTestItem.sPortB_Tip = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Tip].ToString().Trim();

                    arrTestItem.sTestFunction = m_dtTestItem.Rows[i][clsTestItem.chn_TestFunction].ToString().Trim();

                    //FAD
                    arrTestItem.sMarkers = m_dtTestItem.Rows[i][clsTestItem.chn_sMarkers].ToString().Trim();
                    arrTestItem.sAntennaType = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim());
                    arrTestItem.sTestType = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sTestType].ToString().Trim());
                    arrTestItem.sTestMethod = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sTestMethod].ToString().Trim());


                    if (!GetFreqRange(arrTestItem.sFreq, ref arrTestItem.f1, ref arrTestItem.f2))
                    {//频率拆分新方法
                        MessageBox.Show("频率范围" + arrTestItem.sFreq + "解析失败,请参考'420MHz-2010MHz' ");
                        return false;
                    }

                    #endregion

                    #region RandomValue Items
                    //if (arrTestItem.sTestFlag != "True")
                    //{//对于不测试项，如果随机项有双引号则直接填写，否则进行随机取结果处理
                    //    if (arrTestItem.sRandom == "" || (arrTestItem.sRandom.IndexOf(",") == -1 && arrTestItem.sRandom.IndexOf('"') == -1))
                    //    {
                    //        MessageBox.Show("测试项 " + i + " 无效的取值范围: " + arrTestItem.sRandom + ",请参考: 80,105 ");
                    //        this.BeginInvoke(new EventHandler(ShowText), "\r\n " + i + " - " + "xxx 跳过无效测试项");
                    //        continue;
                    //    }

                    //    string strRandom = arrTestItem.sRandom;
                    //    string[] sContent = strRandom.Split('"');
                    //    if (sContent.Length == 3)
                    //    {//直接显示的内容，例如"pass"
                    //        clsInsertRow aInsertRow = new clsInsertRow();
                    //        aInsertRow.dgv = dgvTest;
                    //        aInsertRow.iRow = i;
                    //        aInsertRow.sValue = sContent[1];
                    //        aInsertRow.sResult = GDefine.ContentPass;

                    //        this.BeginInvoke(new EventHandler(FillTestValue), aInsertRow);
                    //    }
                    //    else
                    //    {
                    //        try
                    //        {
                    //            Regex reg = new Regex(@"-?(\d+)\.(\d+)|-?(\d+)");
                    //            MatchCollection ms0 = reg.Matches(strRandom);

                    //            float r1 = float.Parse(ms0[0].Value) * 100;
                    //            float r2 = float.Parse(ms0[1].Value) * 100;
                    //            //以时间为种子的短时间无法产生不重复随机，只能用guid  
                    //            Random randomVal = new Random(Guid.NewGuid().GetHashCode());
                    //            if (r1 < r2)
                    //                Val = randomVal.Next((int)r1, (int)r2) / 100f;
                    //            else
                    //                Val = randomVal.Next((int)r2, (int)r1) / 100f;
                    //            ValResult vr0 = new ValResult();
                    //            vr0.Val = Val;
                    //            vr0.No = i + 1;
                    //            vr0.sResult = GDefine.ContentPass;
                    //            vr0.Val2 = Val2;

                    //            if (ms0.Count == 4)
                    //            {
                    //                r1 = float.Parse(ms0[2].Value) * 100;
                    //                r2 = float.Parse(ms0[3].Value) * 100;
                    //                if (r1 < r2)
                    //                    Val = randomVal.Next((int)r1, (int)r2) / 100f;
                    //                else
                    //                    Val = randomVal.Next((int)r2, (int)r1) / 100f;
                    //                vr0.Val2 = Val;
                    //            }

                    //            clsInsertRow aInsertRow = new clsInsertRow();
                    //            aInsertRow.dgv = dgvTest;
                    //            aInsertRow.iRow = i;
                    //            aInsertRow.sValue = vr0.Val.ToString();
                    //            aInsertRow.sResult = vr0.sResult;

                    //            this.BeginInvoke(new EventHandler(FillTestValue), aInsertRow);
                    //            //FillTestValue(i, vr0.Val.ToString(), vr0.sResult);
                    //        }
                    //        catch (Exception ex)
                    //        {
                    //            //Insert_Standard_ErrorLog.Insert("LoadConfig", "LoadConfig Error --> " + ex.Message);
                    //            MessageBox.Show("ContTest err Random" + ex.Message);
                    //        }
                    //    }

                    //    continue;
                    //}
                    #endregion

                    #region 非本次换线对应的测试项
                    //if (/* m_Instr.Switch_Type != (int)SwitchType.SWITCH_NONE && */arrTestItem.sRandom != arrTestItem.iTestCount.ToString())
                    //{//如果是自动切换则跳过一些非本次换线对应的测试项
                    //    if (aTraceTest.iTraceArrNum != 0)
                    //    { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                    //        //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                    //        int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB,
                    //                                          ref m_sCurReg, ref m_sLastReg,
                    //                                          ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                    //        if (iRetbefore == 2)
                    //            continue;
                    //        else if (iRetbefore == 0)
                    //            return false;

                    //        if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                    //        {
                    //            if (!TestTrace(aTraceTest, ref m_bTotalResult))
                    //            {
                    //                return false;
                    //            }
                    //        }
                    //        else
                    //        {
                    //            if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                    //            {
                    //                return false;
                    //            }
                    //        }
                    //    }
                    //    continue;
                    //}
                    #endregion

                    //取值模式，GetValueMode 
                    //一种，GetValueMode = 0;测试模式0时，根据频率设置起止频段，然后取这一段的最优点，
                    //二种，GetValueMode = 1;测试模式1时，根据 当前的BAND，如果是类似于 0-8500 则用segment取值，
                    //三种，GetValueMode = 2;测试模式1时，根据 当前的BAND，如果是类似于 1830-1880 则集中trace取值,包括单点取值
                    //四种，GetValueMode = 4;测试模式1时，

                    if (m_cProject.sNewTestMode == "1" || m_cProject.sNewTestMode == "2")
                    {//新的测试模式1时
                        if (arrTestItem.sBand.Trim() == "")
                        {//
                            this.BeginInvoke(new EventHandler(ShowText), "必测项" + i + " 未输入校准频段\r\n");
                            continue;
                        }

                        if (arrTestItem.sBand[0] == '0' && arrTestItem.sBand[1] == '-')
                        {//如果是全频段测试，从segment table 中取点数

                            #region 全频段segment测试
                            //int iPointStart = 0, iPointEnd = 0;
                            //if (aTraceTest.iTraceArrNum != 0)
                            //{ //把之前累计的trace进行一次统一处理
                            //    //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                            //    int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                            //                                                 aTraceTest.arrTestItem[0]);
                            //    if (iRetbefore == 2)
                            //        continue;
                            //    else if (iRetbefore == 0)
                            //        return false;
                            //    TestTrace(aTraceTest, ref m_bTotalResult);
                            //}
                            ////再处理segment
                            ////测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                            //int iRetnow = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                            //                                                 arrTestItem);
                            //if (iRetnow == 2)
                            //    continue;
                            //else if (iRetnow == 0)
                            //    return false;
                            //iGetValueMode = 1;
                            ////需要根据频率，获取对应segment表中的点数对应的值

                            //if (!GetPointFromSegment(dsSegment.Tables[0], arrTestItem.sFreq, ref iPointStart, ref iPointEnd))
                            //{
                            //    this.BeginInvoke(new EventHandler(ShowText), "Segment表取点失败，请检查格式!\r\n");
                            //    return false; ;
                            //}
                            //NewTestMode(ref sbFData, ref fArray, iPointStart, iPointEnd - iPointStart + 1, iGetValueMode, bSameCalFileTest,
                            //    arrTestItem.sFormatType, arrTestItem.sTestPortType, arrTestItem.f1, arrTestItem.f2,
                            //    ref InstrLow, ref InstrHigh);
                            #endregion

                        }
                        else
                        {//否则直接去trace中的值,增加智能判断模式，统一保存到数组，当遇到非trace时从数组取出，统一打trace取值。

                            #region trace测试

                            iGetValueMode = 2;
                            if (aTraceTest.iTraceArrNum == 0)
                            {//新的trace测试
                                aTraceTest.sTestItem = arrTestItem.sTestItem;
                                aTraceTest.sFormatType = arrTestItem.sFormatType;
                                aTraceTest.sTestPortType = arrTestItem.sTestPortType;

                                aTraceTest.sBand = arrTestItem.sBand;
                                aTraceTest.sPortA = arrTestItem.sPortA;
                                aTraceTest.sPortB = arrTestItem.sPortB;
                                aTraceTest.f1 = arrTestItem.f1;////要求同时测试的trace必须是同一个频率段
                                aTraceTest.f2 = arrTestItem.f2;
                                aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                                aTraceTest.iTraceArrNum++;

                                //RCU控制字段
                                aTraceTest.sPortA_Angle = arrTestItem.sPortA_Angle;
                                aTraceTest.sPortB_Angle = arrTestItem.sPortB_Angle;
                                aTraceTest.sPortA_RCU = arrTestItem.sPortA_RCU;
                                aTraceTest.sPortB_RCU = arrTestItem.sPortB_RCU;
                                aTraceTest.sTestFunction = arrTestItem.sTestFunction;
                            }
                            //else
                            //{
                            //    if (aTraceTest.sTestName == arrTestItem.sTestName &&
                            //        aTraceTest.sFormatType == arrTestItem.sFormatType &&
                            //        aTraceTest.sTestPortType == arrTestItem.sTestPortType &&

                            //        aTraceTest.sBand == arrTestItem.sBand &&
                            //        aTraceTest.sPortA == arrTestItem.sPortA &&
                            //        aTraceTest.sPortB == arrTestItem.sPortB &&
                            //        aTraceTest.f1 == arrTestItem.f1 &&
                            //        aTraceTest.f2 == arrTestItem.f2 &&
                            //        //判断RCU字段
                            //        aTraceTest.sPortA_Angle == arrTestItem.sPortA_Angle &&
                            //        aTraceTest.sPortB_Angle == arrTestItem.sPortB_Angle &&
                            //        aTraceTest.sPortA_RCU == arrTestItem.sPortA_RCU &&
                            //        aTraceTest.sPortB_RCU == arrTestItem.sPortB_RCU &&
                            //        aTraceTest.sTestFunction == arrTestItem.sTestFunction)
                            //    {//存起来一起处理
                            //        aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                            //        aTraceTest.iTraceArrNum++;
                            //    }
                            //    else
                            //    {//端口改变或带宽改变，则进行一次统一处理，并重新存储
                            //        //进行一次统一处理
                            //        //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                            //        int iRet = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                            //                     aTraceTest.arrTestItem[0]);
                            //        if (iRet == 2)
                            //            continue;
                            //        else if (iRet == 0)
                            //            return false;

                            //        //将存储的trace一并测试
                            //        if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                            //        {
                            //            if (!TestTrace(aTraceTest, ref m_bTotalResult))
                            //            {
                            //                return false;
                            //            }
                            //        }
                            //        else
                            //        {
                            //            if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                            //            {
                            //                return false;
                            //            }
                            //        }

                            //        //并重新存储
                            //        aTraceTest.iTraceArrNum = 0;
                            //        aTraceTest.sBand = arrTestItem.sBand;
                            //        aTraceTest.sPortA = arrTestItem.sPortA;
                            //        aTraceTest.sPortB = arrTestItem.sPortB;
                            //        aTraceTest.f1 = arrTestItem.f1;////要求同时测试的trace必须是同一个频率段
                            //        aTraceTest.f2 = arrTestItem.f2;
                            //        aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                            //        aTraceTest.iTraceArrNum++;
                            //        //并重新存储RCU控制字段
                            //        aTraceTest.sPortA_Angle = arrTestItem.sPortA_Angle;
                            //        aTraceTest.sPortB_Angle = arrTestItem.sPortB_Angle;
                            //        aTraceTest.sPortA_RCU = arrTestItem.sPortA_RCU;
                            //        aTraceTest.sPortB_RCU = arrTestItem.sPortB_RCU;
                            //        aTraceTest.sTestFunction = arrTestItem.sTestFunction;
                            //    }
                            //}

                            if (/*i == num - 1 &&*/ aTraceTest.iTraceArrNum != 0)
                            { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                                //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                                int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg,
                                                                  ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                                if (iRetbefore == 2)
                                    return false;// continue;
                                else if (iRetbefore == 0)
                                    return false;



                                if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                                {
                                    return false;
                                }

                            }
                            aTraceTest.iTraceArrNum = 0;
                            continue;

                            #endregion

                        }
                    }

                    if (arrTestItem.sFormatType == "DISP_DELA")
                    {
                        InstrLow = InstrLow * (float)Math.Pow(10, 9);
                        InstrHigh = InstrHigh * (float)Math.Pow(10, 9);
                    }
                    this.BeginInvoke(new EventHandler(ShowText), "ROW_" + i + ": InsLo=" + InstrLow + ", InsHi=" + InstrHigh + "\r\n");

                    DealResult(arrTestItem, InstrLow, InstrHigh, ref m_bTotalResult);
                }
                #endregion

                #region  for num
                //int i = 0;
                //for (i = 0; i < num; i++)
                //{
                //    if (m_bNeedQuit)
                //        return false;

                //    #region 筛选测试项处理
                //    //获取换线次数
                //    int iChange = Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_Index].ToString().Trim());
                //    if (!m_productObj.enableConfig[i] || iChangeCount != iChange || !m_productObj.enableTestItem[i])
                //    {
                //        if (i == num - 1)
                //        {
                //            if (aTraceTest.iTraceArrNum != 0)
                //            { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                //                //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                //                int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB,
                //                                                  ref m_sCurReg, ref m_sLastReg,
                //                                                  ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                //                if (iRetbefore == 2)
                //                    continue;
                //                else if (iRetbefore == 0)
                //                    return false;
                //                if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                //                {
                //                    if (!TestTrace(aTraceTest, ref m_bTotalResult))
                //                    {
                //                        return false;
                //                    }
                //                }
                //                else
                //                {
                //                    if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                //                    {
                //                        return false;
                //                    }
                //                }

                //            }
                //        }
                //        continue;
                //    }
                //    #endregion

                //    //this.Invoke(new EventHandler(ShowProcess));

                //    float Val;
                //    float Val2 = 0;
                //    int power = 10;

                //    #region 取值和预处理
                //    float InstrHigh = 999;
                //    float InstrLow = 999;
                //    clsTestItem arrTestItem = new clsTestItem();
                //    arrTestItem.iTestIndex = i;
                //    arrTestItem.sTestItem = m_dtTestItem.Rows[i][clsTestItem.chn_ItemName].ToString().Trim();
                //    arrTestItem.sTestName = m_dtTestItem.Rows[i][clsTestItem.chn_ParamName].ToString().Trim();
                //    arrTestItem.sFactSpec = m_dtTestItem.Rows[i][clsTestItem.chn_FactSpec].ToString().Trim();//内控要求 ≤1.43dB
                //    arrTestItem.sInstrCtrl = m_dtTestItem.Rows[i][clsTestItem.chn_InstrCtrl].ToString();//仪表特殊控制
                //    arrTestItem.sFreq = m_dtTestItem.Rows[i][clsTestItem.chn_Freq].ToString().Trim();//1830-1880MHz //Freq
                //    arrTestItem.sRandom = m_dtTestItem.Rows[i][clsTestItem.chn_TestNo].ToString().Trim();
                //    arrTestItem.sTestFlag = m_dtTestItem.Rows[i][clsTestItem.chn_Done].ToString().Trim();
                //    arrTestItem.sPortA = m_dtTestItem.Rows[i][clsTestItem.chn_PortA].ToString().Trim();//GetStrPortAB(iTestCount, );//1端口连接 ANT1//并对应开关切换表获得端口号，以便调用校准文件
                //    arrTestItem.sPortB = m_dtTestItem.Rows[i][clsTestItem.chn_PortB].ToString().Trim();//GetStrPortAB(iTestCount, );//2端口连接 TXA1

                //    arrTestItem.sTestPortType = m_dtTestItem.Rows[i][clsTestItem.chn_PortType].ToString().Trim();//测试内容 S21//GetSParamStr(
                //    arrTestItem.sFormatType = m_dtTestItem.Rows[i][clsTestItem.chn_FormatType].ToString().Trim();//测试数据2 DISP_LOGM
                //    arrTestItem.sReport = m_dtTestItem.Rows[i][clsTestItem.chn_Report].ToString().Trim();//报表内容 最小值的绝对值
                //    arrTestItem.sBand = m_dtTestItem.Rows[i][clsTestItem.chn_Band].ToString().Trim();//校准带宽

                //    arrTestItem.iTestCount = iTestCount;
                //    arrTestItem.power = power;

                //    //RCU控制字段
                //    arrTestItem.sPortA_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Angle].ToString().Trim();
                //    arrTestItem.sPortB_Angle = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Angle].ToString().Trim();
                //    arrTestItem.sPortA_RCU = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_RCU].ToString().Trim();
                //    arrTestItem.sPortB_RCU = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_RCU].ToString().Trim();

                //    arrTestItem.sPortA_Tip = m_dtTestItem.Rows[i][clsTestItem.chn_PortA_Tip].ToString().Trim();
                //    arrTestItem.sPortB_Tip = m_dtTestItem.Rows[i][clsTestItem.chn_PortB_Tip].ToString().Trim();

                //    arrTestItem.sTestFunction = m_dtTestItem.Rows[i][clsTestItem.chn_TestFunction].ToString().Trim();

                //    //FAD
                //    arrTestItem.sMarkers = m_dtTestItem.Rows[i][clsTestItem.chn_sMarkers].ToString().Trim();
                //    arrTestItem.sAntennaType = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim());
                //    arrTestItem.sTestType = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sTestType].ToString().Trim());
                //    arrTestItem.sTestMethod = Convert.ToInt16(m_dtTestItem.Rows[i][clsTestItem.chn_sTestMethod].ToString().Trim());


                //    if (!GetFreqRange(arrTestItem.sFreq, ref arrTestItem.f1, ref arrTestItem.f2))
                //    {//频率拆分新方法
                //        MessageBox.Show("频率范围" + arrTestItem.sFreq + "解析失败,请参考'420MHz-2010MHz' ");
                //        return false;
                //    }

                //    #endregion

                //    #region RandomValue Items

                //    if (arrTestItem.sTestFlag != "True")
                //    {//对于不测试项，如果随机项有双引号则直接填写，否则进行随机取结果处理
                //        if (arrTestItem.sRandom == "" || (arrTestItem.sRandom.IndexOf(",") == -1 && arrTestItem.sRandom.IndexOf('"') == -1))
                //        {
                //            MessageBox.Show("测试项 " + i + " 无效的取值范围: " + arrTestItem.sRandom + ",请参考: 80,105 ");
                //            this.BeginInvoke(new EventHandler(ShowText), "\r\n " + i + " - " + "xxx 跳过无效测试项");
                //            continue;
                //        }

                //        string strRandom = arrTestItem.sRandom;
                //        string[] sContent = strRandom.Split('"');
                //        if (sContent.Length == 3)
                //        {//直接显示的内容，例如"pass"
                //            clsInsertRow aInsertRow = new clsInsertRow();
                //            aInsertRow.dgv = dgvTest;
                //            aInsertRow.iRow = i;
                //            aInsertRow.sValue = sContent[1];
                //            aInsertRow.sResult = GDefine.ContentPass;

                //            this.BeginInvoke(new EventHandler(FillTestValue), aInsertRow);
                //        }
                //        else
                //        {
                //            try
                //            {
                //                Regex reg = new Regex(@"-?(\d+)\.(\d+)|-?(\d+)");
                //                MatchCollection ms0 = reg.Matches(strRandom);

                //                float r1 = float.Parse(ms0[0].Value) * 100;
                //                float r2 = float.Parse(ms0[1].Value) * 100;
                //                //以时间为种子的短时间无法产生不重复随机，只能用guid  
                //                Random randomVal = new Random(Guid.NewGuid().GetHashCode());
                //                if (r1 < r2)
                //                    Val = randomVal.Next((int)r1, (int)r2) / 100f;
                //                else
                //                    Val = randomVal.Next((int)r2, (int)r1) / 100f;
                //                ValResult vr0 = new ValResult();
                //                vr0.Val = Val;
                //                vr0.No = i + 1;
                //                vr0.sResult = GDefine.ContentPass;
                //                vr0.Val2 = Val2;

                //                if (ms0.Count == 4)
                //                {
                //                    r1 = float.Parse(ms0[2].Value) * 100;
                //                    r2 = float.Parse(ms0[3].Value) * 100;
                //                    if (r1 < r2)
                //                        Val = randomVal.Next((int)r1, (int)r2) / 100f;
                //                    else
                //                        Val = randomVal.Next((int)r2, (int)r1) / 100f;
                //                    vr0.Val2 = Val;
                //                }

                //                clsInsertRow aInsertRow = new clsInsertRow();
                //                aInsertRow.dgv = dgvTest;
                //                aInsertRow.iRow = i;
                //                aInsertRow.sValue = vr0.Val.ToString();
                //                aInsertRow.sResult = vr0.sResult;

                //                this.BeginInvoke(new EventHandler(FillTestValue), aInsertRow);
                //                //FillTestValue(i, vr0.Val.ToString(), vr0.sResult);
                //            }
                //            catch (Exception ex)
                //            {
                //                //Insert_Standard_ErrorLog.Insert("LoadConfig", "LoadConfig Error --> " + ex.Message);
                //                MessageBox.Show("ContTest err Random" + ex.Message);
                //            }
                //        }

                //        continue;
                //    }

                //    #endregion

                //    #region 非本次换线对应的测试项
                //    if (/* m_Instr.Switch_Type != (int)SwitchType.SWITCH_NONE && */arrTestItem.sRandom != arrTestItem.iTestCount.ToString())
                //    {//如果是自动切换则跳过一些非本次换线对应的测试项
                //        if (aTraceTest.iTraceArrNum != 0)
                //        { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                //            //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                //            int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB,
                //                                              ref m_sCurReg, ref m_sLastReg,
                //                                              ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                //            if (iRetbefore == 2)
                //                continue;
                //            else if (iRetbefore == 0)
                //                return false;

                //            if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                //            {
                //                if (!TestTrace(aTraceTest, ref m_bTotalResult))
                //                {
                //                    return false;
                //                }
                //            }
                //            else
                //            {
                //                if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                //                {
                //                    return false;
                //                }
                //            }
                //        }
                //        continue;
                //    }
                //    #endregion

                //    //取值模式，GetValueMode 
                //    //一种，GetValueMode = 0;测试模式0时，根据频率设置起止频段，然后取这一段的最优点，
                //    //二种，GetValueMode = 1;测试模式1时，根据 当前的BAND，如果是类似于 0-8500 则用segment取值，
                //    //三种，GetValueMode = 2;测试模式1时，根据 当前的BAND，如果是类似于 1830-1880 则集中trace取值,包括单点取值
                //    //四种，GetValueMode = 4;测试模式1时，

                //    if (m_cProject.sNewTestMode == "1" || m_cProject.sNewTestMode == "2")
                //    {//新的测试模式1时
                //        if (arrTestItem.sBand.Trim() == "")
                //        {//
                //            this.BeginInvoke(new EventHandler(ShowText), "必测项" + i + " 未输入校准频段\r\n");
                //            continue;
                //        }

                //        if (arrTestItem.sBand[0] == '0' && arrTestItem.sBand[1] == '-')
                //        {//如果是全频段测试，从segment table 中取点数

                //            #region 全频段segment测试
                //            //int iPointStart = 0, iPointEnd = 0;
                //            //if (aTraceTest.iTraceArrNum != 0)
                //            //{ //把之前累计的trace进行一次统一处理
                //            //    //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                //            //    int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                //            //                                                 aTraceTest.arrTestItem[0]);
                //            //    if (iRetbefore == 2)
                //            //        continue;
                //            //    else if (iRetbefore == 0)
                //            //        return false;
                //            //    TestTrace(aTraceTest, ref m_bTotalResult);
                //            //}
                //            ////再处理segment
                //            ////测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                //            //int iRetnow = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                //            //                                                 arrTestItem);
                //            //if (iRetnow == 2)
                //            //    continue;
                //            //else if (iRetnow == 0)
                //            //    return false;
                //            //iGetValueMode = 1;
                //            ////需要根据频率，获取对应segment表中的点数对应的值

                //            //if (!GetPointFromSegment(dsSegment.Tables[0], arrTestItem.sFreq, ref iPointStart, ref iPointEnd))
                //            //{
                //            //    this.BeginInvoke(new EventHandler(ShowText), "Segment表取点失败，请检查格式!\r\n");
                //            //    return false; ;
                //            //}
                //            //NewTestMode(ref sbFData, ref fArray, iPointStart, iPointEnd - iPointStart + 1, iGetValueMode, bSameCalFileTest,
                //            //    arrTestItem.sFormatType, arrTestItem.sTestPortType, arrTestItem.f1, arrTestItem.f2,
                //            //    ref InstrLow, ref InstrHigh);
                //            #endregion

                //        }
                //        else
                //        {//否则直接去trace中的值,增加智能判断模式，统一保存到数组，当遇到非trace时从数组取出，统一打trace取值。

                //            #region trace测试

                //            iGetValueMode = 2;
                //            if (aTraceTest.iTraceArrNum == 0)
                //            {//新的trace测试
                //                aTraceTest.sTestItem = arrTestItem.sTestItem;
                //                aTraceTest.sFormatType = arrTestItem.sFormatType;
                //                aTraceTest.sTestPortType = arrTestItem.sTestPortType;

                //                aTraceTest.sBand = arrTestItem.sBand;
                //                aTraceTest.sPortA = arrTestItem.sPortA;
                //                aTraceTest.sPortB = arrTestItem.sPortB;
                //                aTraceTest.f1 = arrTestItem.f1;////要求同时测试的trace必须是同一个频率段
                //                aTraceTest.f2 = arrTestItem.f2;
                //                aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                //                aTraceTest.iTraceArrNum++;

                //                //RCU控制字段
                //                aTraceTest.sPortA_Angle = arrTestItem.sPortA_Angle;
                //                aTraceTest.sPortB_Angle = arrTestItem.sPortB_Angle;
                //                aTraceTest.sPortA_RCU = arrTestItem.sPortA_RCU;
                //                aTraceTest.sPortB_RCU = arrTestItem.sPortB_RCU;
                //                aTraceTest.sTestFunction = arrTestItem.sTestFunction;
                //            }
                //            else
                //            {
                //                if (aTraceTest.sBand == arrTestItem.sBand &&
                //                    aTraceTest.sPortA == arrTestItem.sPortA &&
                //                    aTraceTest.sPortB == arrTestItem.sPortB &&
                //                    aTraceTest.f1 == arrTestItem.f1 &&
                //                    aTraceTest.f2 == arrTestItem.f2 &&
                //                    //判断RCU字段
                //                    aTraceTest.sPortA_Angle == arrTestItem.sPortA_Angle &&
                //                    aTraceTest.sPortB_Angle == arrTestItem.sPortB_Angle &&
                //                    aTraceTest.sPortA_RCU == arrTestItem.sPortA_RCU &&
                //                    aTraceTest.sPortB_RCU == arrTestItem.sPortB_RCU &&
                //                    aTraceTest.sTestFunction == arrTestItem.sTestFunction)
                //                {//存起来一起处理
                //                    aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                //                    aTraceTest.iTraceArrNum++;
                //                }
                //                else
                //                {//端口改变或带宽改变，则进行一次统一处理，并重新存储
                //                    //进行一次统一处理
                //                    //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                //                    int iRet = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg, ref bSameCalFileTest,
                //                                 aTraceTest.arrTestItem[0]);
                //                    if (iRet == 2)
                //                        continue;
                //                    else if (iRet == 0)
                //                        return false;

                //                    //将存储的trace一并测试
                //                    if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                //                    {
                //                        if (!TestTrace(aTraceTest, ref m_bTotalResult))
                //                        {
                //                            return false;
                //                        }
                //                    }
                //                    else
                //                    {
                //                        if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                //                        {
                //                            return false;
                //                        }
                //                    }

                //                    //并重新存储
                //                    aTraceTest.iTraceArrNum = 0;
                //                    aTraceTest.sBand = arrTestItem.sBand;
                //                    aTraceTest.sPortA = arrTestItem.sPortA;
                //                    aTraceTest.sPortB = arrTestItem.sPortB;
                //                    aTraceTest.f1 = arrTestItem.f1;////要求同时测试的trace必须是同一个频率段
                //                    aTraceTest.f2 = arrTestItem.f2;
                //                    aTraceTest.arrTestItem[aTraceTest.iTraceArrNum] = arrTestItem;
                //                    aTraceTest.iTraceArrNum++;
                //                    //并重新存储RCU控制字段
                //                    aTraceTest.sPortA_Angle = arrTestItem.sPortA_Angle;
                //                    aTraceTest.sPortB_Angle = arrTestItem.sPortB_Angle;
                //                    aTraceTest.sPortA_RCU = arrTestItem.sPortA_RCU;
                //                    aTraceTest.sPortB_RCU = arrTestItem.sPortB_RCU;
                //                    aTraceTest.sTestFunction = arrTestItem.sTestFunction;
                //                }
                //            }

                //            if (i == num - 1 && aTraceTest.iTraceArrNum != 0)
                //            { //在跳过所有非本次测试项之前，如果有trace测试，需要进行处理//把之前累计的trace进行一次统一处理
                //                //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++
                //                int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg,
                //                                                  ref bSameCalFileTest, aTraceTest.arrTestItem[0]);
                //                if (iRetbefore == 2)
                //                    continue;
                //                else if (iRetbefore == 0)
                //                    return false;

                //                if (Convert.ToInt32(m_dtTestItem.Rows[i][clsTestItem.chn_sAntennaType].ToString().Trim()) == (int)AntennaType.NUMAL)
                //                {
                //                    if (!TestTrace(aTraceTest, ref m_bTotalResult))
                //                    {
                //                        return false;
                //                    }
                //                }
                //                else
                //                {
                //                    if (!TestTraceTD(aTraceTest, ref m_bTotalResult))
                //                    {
                //                        return false;
                //                    }
                //                }

                //            }

                //            continue;

                //            #endregion

                //        }
                //    }

                //    if (arrTestItem.sFormatType == "DISP_DELA")
                //    {
                //        InstrLow = InstrLow * (float)Math.Pow(10, 9);
                //        InstrHigh = InstrHigh * (float)Math.Pow(10, 9);
                //    }
                //    this.BeginInvoke(new EventHandler(ShowText), "ROW_" + i + ": InsLo=" + InstrLow + ", InsHi=" + InstrHigh + "\r\n");

                //    DealResult(arrTestItem, InstrLow, InstrHigh, ref m_bTotalResult);
                //}
                #endregion
            }

            return true;
        }
        int ReadCalAndSwitch(ref string m_sLastPortA, ref string m_sLastPortB,
                             ref string m_sCurReg, ref string m_sLastReg,
                             ref bool bSameCalFileTest, clsTestItem arrTestItem)
        {
            if (m_AntennaType == AntennaType.TD && (arrTestItem.sTestItem == "幅度一致性" || arrTestItem.sTestItem == "相位一致性"))
            {
                return 1;
            }
            int ret = 1;
            //测试之前再读校准文件和开关切换+++++++++++++++++++++++++++++++++++++++++++++++

            #region 设置开关
            if (IsSwitch)
            {//设开关，目前开关切换有两种方式，1开关箱根据方案切换表自动切换，2，手动根据测试项中的端口切换
                if (m_Instr.Switch_Type == (int)SwitchType.SWITCH_NONE)
                { //手动换线
                    if (m_sLastPortA != arrTestItem.sPortA || m_sLastPortB != arrTestItem.sPortB)
                    {//链路变化时切换一下
                        //DataTable dtManual = new DataTable();
                        //dtManual.Columns.Add("Port1");
                        //dtManual.Columns.Add("Port2");
                        //DataRow aNewRow = dtManual.NewRow();
                        //aNewRow["Port1"] = arrTestItem.sPortA;
                        //aNewRow["Port2"] = arrTestItem.sPortB;
                        //dtManual.Rows.Add(aNewRow);

                        //GetNameFrm diagramFrm = new GetNameFrm(dtManual, 0, m_curRemarkText, m_cProject.iCodeLen);
                        this.Invoke(new ThreadStart(delegate
                        {
                            string t1 = "";
                            string t2 = "";
                            if (arrTestItem.sPortA_Tip == "" || arrTestItem.sPortB_Tip == "")
                            {
                                t1 = arrTestItem.sPortA_RCU;
                                t2 = arrTestItem.sPortB_RCU;
                            }
                            else
                            {
                                t1 = arrTestItem.sPortA_Tip;
                                t2 = arrTestItem.sPortB_Tip;
                            }

                            //if (MessageBox.Show("请连接端口: \r\n" +
                            //                    "P1 ==> " + arrTestItem.sPortA_RCU + ", " +
                            //                    "P2 ===> " + arrTestItem.sPortB_RCU, "提示",
                            //                    MessageBoxButtons.OKCancel) == DialogResult.OK)
                            if (MessageBox.Show("请连接端口: \r\n" +
                                            "P1 ==> " + t1 + ", " +
                                            "P2 ==> " + t2, "提示",
                                            MessageBoxButtons.OKCancel) == DialogResult.OK)
                            {
                                ret = 1;
                                //return 1;
                            }
                            else
                            {
                                m_bManualStop = true;
                                ret = 0;
                                //return 0;
                            }

                        }));

                        if (ret == 1)
                        {
                            m_sLastPortA = arrTestItem.sPortA;
                            m_sLastPortB = arrTestItem.sPortB;
                        }
                    }
                }
                else
                {//自动切换

                    //if (arrTestItem.sRandom != arrTestItem.iTestCount.ToString())//如果是自动切换则跳过一些非本次换线对应的测试项需要在外面提取处理
                    //    return 2;

                    string sPortA = GetStrPortAB(arrTestItem.iTestCount, arrTestItem.sPortA);//m_dtTestItem.Rows[i][8].ToString().Trim();//1端口连接 ANT1//并对应开关切换表获得端口号，以便调用校准文件
                    string sPortB = GetStrPortAB(arrTestItem.iTestCount, arrTestItem.sPortB); //m_dtTestItem.Rows[i][9].ToString().Trim();//2端口连接 TXA1
                    if (sPortA == null || sPortB == null)
                    {
                        this.BeginInvoke(new EventHandler(ShowText), "测试项 " + (arrTestItem.iTestIndex + 1) + " 无法找到对应的端口" + arrTestItem.sPortA + "," + arrTestItem.sPortB);
                        return 0;
                    }
                    arrTestItem.sPortA = sPortA;
                    arrTestItem.sPortB = sPortB;
                    if (m_sLastPortA != arrTestItem.sPortA || m_sLastPortB != arrTestItem.sPortB)
                    {//测试链路变化时，切换一次
                        if (!m_CLoadSwitch.Select_Switch_port(Convert.ToInt32(arrTestItem.sPortA),
                                                              Convert.ToInt32(arrTestItem.sPortB), SwitchNeedTime))
                        {
                            this.BeginInvoke(new EventHandler(ShowText), m_CLoadSwitch.m_sbErr.ToString());
                            return 0;
                        }
                        m_sLastPortA = arrTestItem.sPortA;
                        m_sLastPortB = arrTestItem.sPortB;
                    }
                }
            }

            #endregion

            #region 调用校准文件
            //切换链路后，调用校准文件，目前有三种方式，
            //一种，测试模式0时，根据 频率在哪个范围内+端口号 决定调用2者之一 ZTE-ECAL-0.3-3000-PORT"; "ZTE-ECAL-1650-1950-PORT"，
            //二种，测试模式1时，根据 方案ID+当前的BAND+端口号 决定调用文件//"N12-2227-1950-5240-PORT1-3"; //"N6-2227-1980-5250-PORT2-4"; //"N6-2227-0-8500-PORT2-4";
            //三种，手动时，根据 当前的BAND 决定调用文件 "N2-1982-1992";

            //"N00-1982-1992" //手动时的校准文件
            if (IsVNA)
            {
                if (m_Instr.Switch_Type == (int)SwitchType.SWITCH_NONE)
                { //三种,手动时
                    if (arrTestItem.sBand == null || arrTestItem.sBand == "" || m_cProject.Band.IndexOf(arrTestItem.sBand) == -1)
                    {//如果band为空，或测试项中的band不在方案中
                        this.BeginInvoke(new EventHandler(ShowText),
                            "测试项" + (arrTestItem.iTestIndex + 1) + ",没有Band属性或不在方案中,无法获取校准文件\r\n");
                        return 0;
                    }

                    //m_sCurReg = "N2-" + m_cProject.ProjectId + "-" + arrTestItem.sBand;
                    m_sCurReg = CALREG_ALL_BAND;

                    m_sCurReg = "N2" + "-" + m_cProject.ProjectId + "-" + arrTestItem.sBand + "-PORT1-2";
                }
                else if (m_cProject.sNewTestMode == "1" || m_cProject.sNewTestMode == "2")
                {//二种，测试模式1时//新测试模式中的校准文件
                    if (arrTestItem.sBand == null || arrTestItem.sBand == "" || m_cProject.Band.IndexOf(arrTestItem.sBand) == -1)
                    {//如果band为空，或测试项中的band不在方案中
                        this.BeginInvoke(new EventHandler(ShowText),
                            "测试项" + (arrTestItem.iTestIndex + 1) + ",没有Band属性或不在方案中,无法获取校准文件\r\n");
                        return 2;
                    }
                    if (arrTestItem.sPortA == arrTestItem.sPortB)
                    {
                        m_sCurReg = "N" + (m_Instr.Switch_Count + 1).ToString() + "-" + m_cProject.ProjectId + "-" + arrTestItem.sBand
                    + "-PORT" + "1" + "-" + arrTestItem.sPortB;
                    }
                    else
                    {
                        m_sCurReg = "N" + (m_Instr.Switch_Count + 1).ToString() + "-" + m_cProject.ProjectId + "-" + arrTestItem.sBand
                           + "-PORT" + arrTestItem.sPortA + "-" + arrTestItem.sPortB;
                    }
                }

                if (m_sCurReg != m_sLastReg)
                {//重新启用校准文件
                    if (!m_CInstrVNA.RecallReg(m_sCurReg))
                    {
                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        this.Invoke(new ThreadStart(delegate { MessageBox.Show("未找到状态文件,请校准后重试!", "ERR"); }));
                        return 0;
                    }
                    m_sLastReg = m_sCurReg;
                    bSameCalFileTest = false;
                }
                else
                {
                    bSameCalFileTest = true;//本次测试不再操作仪表，直接取值
                }
            }
            #endregion

            return ret;
            //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        }

        List<clsTraceTest> m_arrTrace_temp = new List<clsTraceTest>();
        clsVNASetting vanLastSet = new clsVNASetting();
        bool TestTraceTD(clsTraceTest arrTrace, ref bool bTotalResult, bool isRetry = false)
        {//将数组中的trace统一测试          
            StringBuilder sbTraceData = new StringBuilder(1);
            float InsLo = 0, InsHi = 0;
            float[] fArray;

            bool bBeforResult = bTotalResult;
            bool bNowAllTraceResult = true;


            ImpCtrl ctlObj = new ImpCtrl();
            ctlObj.bQuit = true;
            ctlObj.bCtrl = true;

            #region 设置4个trace
            //if (vanLastSet.tracCount != 4)
            //{
            if (!m_CInstrVNA.SetTraceCoun(4))
            {
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            }
            //}
            vanLastSet.tracCount = 4;
            /*
            if (!m_CInstrVNA.SetSweepPoints(801))
            {//必须设置点数//当前默认801,不同的测试型号是否相同//mustdo//这步动作放到校准中去做
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            }*/

            //if (!m_CInstrVNA.SetSweepType("LIN"))
            //{
            //    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            //}
            //if (!m_CInstrVNA.SetFrequency(arrTrace.f1, arrTrace.f2))
            //{
            //    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            //}

            #endregion

            for (int tryNum = 0; tryNum < 1; tryNum++)
            {
                //由于只有4个trace可以同时测所以进行分组循环//根据读值需要设置format，s21等读取值
                string count = ""; List<int> traceIndex = new List<int>();
                for (int i = 0; i < arrTrace.iTraceArrNum; i = i + 4)
                {
                    #region 初始化
                    //int[] iLastIFBW, iLastPoints, iLastPower, iLastSmooth;
                    float[] fMax_InsLo = new float[4];
                    float[] fMin_InsHi = new float[4];
                    //iLastIFBW = new int[4];
                    //iLastPoints = new int[4];
                    //iLastPower = new int[4];
                    //iLastSmooth = new int[4];
                    for (int tmp = 0; tmp < 4; tmp++)
                    {
                        //iLastIFBW[tmp] = 0;
                        //iLastPoints[tmp] = 0;
                        //iLastPower[tmp] = 999;
                        //iLastSmooth[tmp] = 999;

                        fMax_InsLo[tmp] = float.MinValue;
                        fMin_InsHi[tmp] = float.MaxValue;
                    }
                    #endregion
                    this.BeginInvoke(new EventHandler(ShowText), i + "\r\n");
                    #region 统一设置

                    for (int k = 0; k < 4; k++)
                    {
                        if (i + k >= arrTrace.iTraceArrNum)
                            break;
                        //count += k + 1 + ",";
                        //trace 1 - k 操作
                        //   if (arrTrace.sFormatType == "DISP_SWR" &&arrTrace.sTestPortType=="S22"&& arrTrace.sPortA_RCU == arrTrace.sPortB_RCU) k++;
                        //if (vanLastSet.TracSel != k + 1 || vanLastSet.meas != arrTrace.arrTestItem[i + k].sTestPortType)
                        //{
                        if (!m_CInstrVNA.SetMeasType(k + 1, arrTrace.arrTestItem[i + k].sTestPortType))
                        {//S21
                            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        }
                        //}
                        //if (vanLastSet.TracSel != k + 1 || vanLastSet.fromat != arrTrace.arrTestItem[i + k].sFormatType)
                        //{
                        if (!m_CInstrVNA.SetDisplayFormat(k + 1, arrTrace.arrTestItem[i + k].sFormatType))
                        {//format//并且选中当前的trace
                            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        }
                        //}
                        //vanLastSet.meas = arrTrace.arrTestItem[i + k].sTestPortType;
                        //vanLastSet.fromat = arrTrace.arrTestItem[i + k].sFormatType;
                        //vanLastSet.TracSel = k + 1;
                    }
                    #endregion
                    do
                    {
                        if (m_bNeedQuit) return false;
                        #region 统一trig
                        if (!m_CInstrVNA.BeforeTrig())
                        {
                            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        }
                        if (!m_CInstrVNA.TrigSingle())
                        {
                            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        }

                        if (!m_CInstrVNA.DisplayAutoScaleAll())
                        {
                            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        }
                        #endregion

                        #region 统一读值
                        for (int k = 0; k < 4; k++)
                        {
                            if (i + k >= arrTrace.iTraceArrNum)
                                break;
                            // if (arrTrace.sFormatType == "DISP_SWR" && arrTrace.sTestPortType == "S22" && arrTrace.sPortA_RCU == arrTrace.sPortB_RCU) k++;
                            //if (vanLastSet.TracSel != k + 1)
                            //{
                            if (!m_CInstrVNA.TraceSel(k + 1))
                            {//选中trace
                                tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
                            }
                            //}
                            //vanLastSet.TracSel = k + 1;

                            #region Mark
                            if (arrTrace.arrTestItem[i + k].sReport == "定点值")
                            {
                                string[] mark = arrTrace.arrTestItem[0].sMarkers.Split(',');
                                float[] markY = new float[mark.Length];
                                for (int m = 0; m < mark.Length; m++)
                                {
                                    //设定mark
                                    if (!m_CInstrVNA.SetMark("MKR_FREQ", PIMFunction.FreqToHz(mark[m]), k + 1))
                                    {
                                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                    }
                                    if (!m_CInstrVNA.GetMarkYValue(out InsLo, k + 1))
                                    {
                                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                    }
                                    InsHi = InsLo;
                                    markY[m] = InsLo;
                                }
                                for (int ii = 0; ii < markY.Length; ii++)
                                {
                                    InsLo = InsLo > markY[ii] ? InsLo : markY[ii];
                                    InsHi = InsHi < markY[ii] ? InsHi : markY[ii];
                                }
                            }
                            else if (arrTrace.arrTestItem[i + k].sReport == "最大值-最小值")
                            {
                                if (arrTrace.arrTestItem[i + k].sTestItem == "幅度一致性" || arrTrace.arrTestItem[0].sTestItem == "相位一致性")
                                {
                                    InsLo = InsHi = float.Parse(m_arrTrace_temp[0].arrTestItem[0].sValue);
                                    List<string> strval = new List<string>();
                                    List<string> portAB = new List<string>();
                                    foreach (var obj in m_arrTrace_temp)
                                    {
                                        if (arrTrace.arrTestItem[i + k].sTestItem == "幅度一致性"
                                            && obj.sTestItem == "耦合"
                                            && obj.arrTestItem[0].sMarkers == arrTrace.arrTestItem[i + k].sMarkers
                                            )
                                        {
                                            strval.Add(obj.arrTestItem[0].sValue);
                                            portAB.Add(obj.arrTestItem[0].sPortA_RCU + ";" + obj.arrTestItem[0].sPortB_RCU);
                                            traceIndex.Add(m_arrTrace_temp.IndexOf(obj));
                                        }
                                        else if (arrTrace.arrTestItem[i + k].sTestItem == "相位一致性"
                                                 && obj.sTestItem == "相位"
                                                 && obj.arrTestItem[0].sMarkers == arrTrace.arrTestItem[i + k].sMarkers
                                                 )
                                        {
                                            strval.Add(obj.arrTestItem[0].sValue);
                                            portAB.Add(obj.arrTestItem[0].sPortA_RCU + ";" + obj.arrTestItem[0].sPortB_RCU);
                                            traceIndex.Add(m_arrTrace_temp.IndexOf(obj));
                                        }

                                        //  strval.Add(obj.arrTestItem[0].sValue);
                                    }

                                    InsLo = InsHi = float.Parse(strval[0]);
                                    for (int a = 0; a < strval.Count; a++)
                                    {
                                        InsLo = InsLo > float.Parse(strval[a]) ? InsLo : float.Parse(strval[a]);
                                        InsHi = InsHi < float.Parse(strval[a]) ? InsHi : float.Parse(strval[a]);
                                    }
                                    //foreach (var obj in m_arrTrace_temp)
                                    //{
                                    //    InsLo = InsLo > float.Parse(obj.arrTestItem[0].sValue) ? InsLo : float.Parse(obj.arrTestItem[0].sValue);
                                    //    InsHi = InsHi < float.Parse(obj.arrTestItem[0].sValue) ? InsHi : float.Parse(obj.arrTestItem[0].sValue);
                                    //}
                                }
                            }
                            else
                            {
                                //下面是mark取点法------------------------------------------------------
                                if (!m_CInstrVNA.SetMark("MKR_MAX", 0, 1))
                                {
                                    tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.SetMark("MKR_MIN", 0, 2))
                                {
                                    tb_Test.AppendText(m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.GetMarkYValue(out InsLo, 1))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.GetMarkYValue(out InsHi, 2))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                //-----------------------------------------------------------------------------*/
                            }
                            this.BeginInvoke(new EventHandler(ShowText), "trace_" + k + ": InsLo=" + InsLo + ", InsHi=" + InsHi + "\r\n");

                            #endregion

                            #region 统一显示到界面
                            if (fMax_InsLo[k] < InsLo)
                                fMax_InsLo[k] = InsLo;
                            if (fMin_InsHi[k] > InsHi)
                                fMin_InsHi[k] = InsHi;

                            bool btemp = bTotalResult;
                            bool bNowResult = DealResult(arrTrace.arrTestItem[i + k], fMax_InsLo[k], fMin_InsHi[k], ref bTotalResult);
                            bNowAllTraceResult &= bNowResult;
                            //bNowAllTraceResult = bNowResult;
                            #endregion

                            #region 恢复IFBW等仪表特殊控制项
                            //if (iLastIFBW[k] != 0)
                            //{
                            //    if (!m_CInstrVNA.SetIFBandWidth(iLastIFBW[k]))
                            //    {
                            //        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                            //    }
                            //}
                            //if (iLastSmooth[k] != 999)
                            //{
                            //    if (!m_CInstrVNA.SetSmooth(Convert.ToString(iLastSmooth[k])))
                            //    {
                            //        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                            //    }
                            //}
                            //if (iLastPoints[k] != 0)
                            //{
                            //    if (!m_CInstrVNA.SetSweepPoints(iLastPoints[k]))
                            //    {
                            //        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                            //    }
                            //}
                            //if (iLastPower[k] != 999)
                            //{
                            //    if (!m_CInstrVNA.SetSweepPoints(iLastPower[k]))
                            //    {
                            //        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                            //    }
                            //}
                            #endregion

                        }
                        #endregion
                    }
                    while (!ctlObj.bQuit);
                }

                #region 重测2
                if (!bNowAllTraceResult)
                {//判断是否重测
                    FrmRetry frmTips = new FrmRetry(true);
                    DialogResult dr = frmTips.ShowDialog();
                    if (dr == DialogResult.No)
                    {//关闭
                        m_bNeedQuit = true;
                        m_bManualStop = true;
                        return false;
                    }
                    else if (dr == DialogResult.Retry)
                    {//重试
                        bNowAllTraceResult = true;
                        if (arrTrace.arrTestItem[0].sTestItem == "幅度一致性" || arrTrace.arrTestItem[0].sTestItem == "相位一致性")
                        {
                            string m_sLastPortA = "", m_sLastPortB = ""; bool bSameCalFileTest = false;//相同的校准文件统一读值标志
                            foreach (var obj in m_arrTrace_temp)
                            {
                                if (traceIndex.IndexOf(m_arrTrace_temp.IndexOf(obj)) > -1)
                                {
                                    int iRetbefore = ReadCalAndSwitch(ref m_sLastPortA, ref m_sLastPortB, ref m_sCurReg, ref m_sLastReg,
                                                                ref bSameCalFileTest, obj.arrTestItem[0]);
                                    if (iRetbefore == 2)
                                        return false;// continue;
                                    else if (iRetbefore == 0)
                                        return false;

                                    TestTraceTD(obj, ref bBeforResult, true);
                                }
                            }
                        }


                        //  isRetry = true;

                        bTotalResult = bBeforResult;
                        tryNum--;
                        continue;
                    }
                    else if (dr == DialogResult.Ignore)
                    {//继续
                    }
                }
                #endregion
            }

            if (arrTrace.arrTestItem[0].sTestItem == "耦合" || arrTrace.arrTestItem[0].sTestItem == "相位")
            {
                if (!isRetry)
                    m_arrTrace_temp.Add(arrTrace.Clone());
            }
            //else
            //{
            //    if (m_arrTrace_temp.Count > 0)
            //        m_arrTrace_temp.Clear();
            //}


            //  bNowAllTraceResult = true;
            if (!isRetry)
                arrTrace.iTraceArrNum = 0;//测试完清空
            return true;
        }

        bool TestTrace(clsTraceTest arrTrace, ref bool bTotalResult)
        {//将数组中的trace统一测试

            StringBuilder sbTraceData = new StringBuilder(1);
            float InsLo, InsHi;
            float[] fArray;

            bool bBeforResult = bTotalResult;
            bool bNowAllTraceResult = true;
            bool bWavefromPass = true;

            ImpCtrl ctlObj = new ImpCtrl();
            ctlObj.bQuit = true;
            ctlObj.bCtrl = true;

            #region 设置4个trace
            if (!m_CInstrVNA.SetTraceCoun(4))
            {
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            }
            /*
            if (!m_CInstrVNA.SetSweepPoints(801))
            {//必须设置点数//当前默认801,不同的测试型号是否相同//mustdo//这步动作放到校准中去做
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            }*/

            if (!m_CInstrVNA.SetSweepType("LIN"))
            {
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            }
            if (!m_CInstrVNA.SetFrequency(arrTrace.f1, arrTrace.f2))
            {
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            }
            #endregion

            for (int tryNum = 0; tryNum < 1; tryNum++)
            {

                #region 调度
                if (arrTrace.sTestFunction == "Continue")
                {
                    ctlObj.bQuit = false;
                    DelContinueSetRCUIndex del_continueSetRCUIndex = new DelContinueSetRCUIndex(continueSetRCUIndex);
                    string sRCUIndex = arrTrace.sPortA_RCU.Substring(0, arrTrace.sPortA_RCU.Length - GDefine.RCU_PORT_NAME.Length);

                    string sMaxAngle = "";
                    string sMinAngle = "";
                    Regex reg = new Regex(@"(\d+|-\d+)-(\d+|-\d+)");
                    var m = reg.Match(arrTrace.sPortA_Angle);
                    if (m.Success && m.Groups.Count == 3)
                    {
                        sMaxAngle = m.Groups[2].Value;
                        sMinAngle = m.Groups[1].Value;
                    }
                    else
                    {
                        MessageBox.Show("配置文件中角度设置错误,请检查!");
                        return false;
                    }
                    int iMinAngle = Convert.ToInt32(sMinAngle);
                    int iMaxAngle = Convert.ToInt32(sMaxAngle);

                    #region 同端口分频测试
                    clsTraceTest m_Continue_lsTraceTestedPrevious = new clsTraceTest();
                    m_Continue_lsTraceTestedPrevious.arrTestItem[0] = new clsTestItem();
                    m_Continue_lsTraceTestedPrevious.arrTestItem[0] = arrTrace.arrTestItem[0];
                    m_Continue_lsTraceTestedPrevious.sPortA_RCU = arrTrace.sPortA_RCU;
                    m_Continue_lsTraceTested.Add(m_Continue_lsTraceTestedPrevious);
                    if (m_Continue_lsTraceTested.Count > 1)
                    {
                        foreach (clsTraceTest tra in m_Continue_lsTraceTested)
                        {
                            string sRCUIndex1 = tra.sPortA_RCU.Substring(0, tra.sPortA_RCU.Length - GDefine.RCU_PORT_NAME.Length);
                            if (tra.arrTestItem[0].sFreq != arrTrace.arrTestItem[0].sFreq && sRCUIndex1 == sRCUIndex)
                            {
                                int iIniAngle = m_isInitMaxAngle ? iMaxAngle : iMinAngle;
                                FrmTips ctl_frm_message = new FrmTips("正在设置端口" + sRCUIndex1 + "角度" + iIniAngle.ToString() + ",请稍等！");
                                if (m_Instr.RCU_Type != 0)
                                {
                                    this.BeginInvoke(new ThreadStart(delegate
                                    {
                                        ctl_frm_message.Show();
                                    }));
                                }
                                continueSetRCUIndex(ctlObj, sRCUIndex, iIniAngle);
                                ctlObj.bQuit = false;
                                if (m_Instr.RCU_Type != 0)
                                {
                                    this.BeginInvoke(new ThreadStart(delegate
                                    {

                                        ctl_frm_message.Close();
                                        ctl_frm_message = null;
                                    }));
                                }
                                break;
                            }
                        }
                    }
                    #endregion

                    int iNeedAngle = !m_isInitMaxAngle ? iMaxAngle : iMinAngle;
                    if (m_dicRCUs[sRCUIndex].angle != iNeedAngle * 10)
                    {
                        if (m_Instr.RCU_Type == 0)
                        {//手动调度
                            this.Invoke(new ThreadStart(delegate
                            {
                                MessageBox.Show(sRCUIndex + " 开始手动调速，请准备(当点击确定后，请手动缓慢的转动角度)!");
                            }));
                        }

                        del_continueSetRCUIndex.BeginInvoke(ctlObj, sRCUIndex, iNeedAngle, null, del_continueSetRCUIndex);
                    }
                    else
                    {
                        ctlObj.bQuit = true;
                        //this.Invoke(new ThreadStart(delegate
                        //{
                        //    MessageBox.Show("角度调整未到预期值！");
                        //    tb_Test.AppendText("RCU: 角度调整未到预期值！");
                        //}));
                        //m_bNeedQuit = true;
                        //return false;
                    }
                }

                #endregion

                List<double> TraceCom0min = new List<double>();
                List<double> TraceCom0max = new List<double>();
                List<double> TraceCom1min = new List<double>();
                List<double> TraceCom1max = new List<double>();
                List<double> TraceCom2min = new List<double>();
                List<double> TraceCom2max = new List<double>();
                int N = 0;

                //由于只有4个trace可以同时测所以进行分组循环//根据读值需要设置format，s21等读取值
                string count = "";
                //do
                //{
                //    if (m_bNeedQuit) return false;
                for (int i = 0; i < arrTrace.iTraceArrNum; i = i + 4)
                {
                    #region 初始化

                    int[] iLastIFBW, iLastPoints, iLastPower, iLastSmooth;
                    float[] fMax_InsLo = new float[4];
                    float[] fMin_InsHi = new float[4];
                    iLastIFBW = new int[4];
                    iLastPoints = new int[4];
                    iLastPower = new int[4];
                    iLastSmooth = new int[4];

                    for (int tmp = 0; tmp < 4; tmp++)
                    {
                        iLastIFBW[tmp] = 0;
                        iLastPoints[tmp] = 0;
                        iLastPower[tmp] = 999;
                        iLastSmooth[tmp] = 999;

                        fMax_InsLo[tmp] = float.MinValue;
                        fMin_InsHi[tmp] = float.MaxValue;
                    }

                    #endregion
                    this.BeginInvoke(new EventHandler(ShowText), i + "\r\n");
                    #region 统一设置
                    for (int k = 0; k < 4; k++)
                    {
                        if (i + k >= arrTrace.iTraceArrNum)
                            break;
                        count += k + 1 + ",";
                        //trace 1 - k 操作
                        if (!m_CInstrVNA.SetMeasType(k + 1, arrTrace.arrTestItem[i + k].sTestPortType))
                        {//S21
                            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        }
                        if (!m_CInstrVNA.SetDisplayFormat(k + 1, arrTrace.arrTestItem[i + k].sFormatType))
                        {//format//并且选中当前的trace
                            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        }
                        if (arrTrace.arrTestItem[i + k].sInstrCtrl != "")
                        {//额外的一些仪表控制，以便实现隔离度等测试
                            string[] arrCtrl = arrTrace.arrTestItem[i + k].sInstrCtrl.Split(';');
                            for (int m = 0; m < arrCtrl.Length; m++)
                            {
                                if (arrCtrl[m] == "")
                                    continue;
                                string[] arrName = arrCtrl[m].Split('=');
                                if (arrName.Length < 2)
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), "无效的仪表控制项:" + arrCtrl[m]);
                                    continue;
                                }
                                if (arrName[0] == "IFBW")
                                {
                                    if (!m_CInstrVNA.GetIFBW(ref iLastIFBW[k]))
                                    {
                                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                    }
                                    if (!m_CInstrVNA.SetIFBandWidth(Convert.ToInt32(arrName[1])))
                                    {
                                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                    }
                                }
                                else if (arrName[0] == "MAKRX")
                                {//根据频率，打mark点
                                    if (!m_CInstrVNA.SetMark("MKR_FREQ", PIMFunction.FreqToHz(arrName[1]), k + 1))
                                    {
                                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                    }
                                }
                                else if (arrName[0] == "SMOOTH")
                                {//设定smooth
                                    if (!m_CInstrVNA.GetSmooth(ref iLastSmooth[k]))
                                    {
                                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                    }
                                    if (!m_CInstrVNA.SetSmooth(arrName[1]))
                                    {
                                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                    }
                                }
                                else if (arrName[0] == "POINTS")
                                {//设定POINT
                                    if (!m_CInstrVNA.GetSweepPoints(ref iLastPoints[k]))
                                    {
                                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                    }
                                    if (!m_CInstrVNA.SetSweepPoints(Convert.ToInt32(arrName[1])))
                                    {
                                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                    }
                                }
                                else if (arrName[0] == "POWER")
                                {//设定power
                                    if (!m_CInstrVNA.GetPower(ref iLastPower[k]))
                                    {
                                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                    }
                                    if (!m_CInstrVNA.SetPower(Convert.ToInt32(arrName[1])))
                                    {
                                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                    }
                                }
                                else
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), "未知的仪表控制列:" + arrCtrl[m]);
                                }
                            }

                        }
                    }
                    #endregion

                    do
                    {
                        if (m_bNeedQuit) return false;

                        #region 统一trig  trig必须保证此次测试所有项目在同一角度
                        if (!m_CInstrVNA.BeforeTrig())
                        {
                            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        }
                        if (!m_CInstrVNA.TrigSingle())
                        {
                            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        }

                        if (!m_CInstrVNA.DisplayAutoScaleAll())
                        {
                            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        }
                        #endregion

                        #region 统一读值
                        for (int k = 0; k < 4; k++)
                        {
                            if (i + k >= arrTrace.iTraceArrNum)
                                break;

                            if (!m_CInstrVNA.TraceSel(k + 1))
                            {//选中trace
                                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                            }

                            #region Mark
                            if (arrTrace.arrTestItem[i + k].sReport == "定点值")
                            {
                                if (!m_CInstrVNA.GetMarkYValue(out InsLo, k + 1))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                InsHi = 0;
                            }
                            else
                            {
                                /*/通过取点法取值在5071C上有bug------------------------------------------------------
                                sbTraceData.Length = 1;
                                if (!m_CInstrVNA.ReadFdata(k + 1, ref sbTraceData))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (sbTraceData.Length == 0)
                                {
                                    InsLo = 0;
                                    InsHi = 0;
                                    continue;
                                }
                                fArray = ToFloatArr(sbTraceData.ToString());

                                int iPointNum = 801;//获取当前仪表的点数；
                                if (!m_CInstrVNA.GetSweepPoints(ref iPointNum))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                InsLo = GetPointMax(fArray, 0, iPointNum);
                                InsHi = GetPointMin(fArray, 0, iPointNum);
                                /*/
                                //下面是mark取点法------------------------------------------------------

                                if (!m_CInstrVNA.SetMark("MKR_MAX", 0, 1))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.SetMark("MKR_MIN", 0, 2))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.GetMarkYValue(out InsLo, 1))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.GetMarkYValue(out InsHi, 2))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                //-----------------------------------------------------------------------------*/
                            }

                            this.BeginInvoke(new EventHandler(ShowText), "trace_" + k + ": InsLo=" + InsLo + ", InsHi=" + InsHi + "\r\n");

                            switch (k)
                            {
                                case 0:
                                    if (arrTrace.arrTestItem[i + k].sTestName.Contains("驻波"))
                                    {
                                        TraceCom0max.Add(Math.Round(InsLo, 2));
                                        TraceCom0min.Add(Math.Round(InsHi, 2));
                                    }
                                    break;
                                case 1:
                                    if (arrTrace.arrTestItem[i + k].sTestName.Contains("驻波"))
                                    {
                                        TraceCom1max.Add(Math.Round(InsLo, 2));
                                        TraceCom1min.Add(Math.Round(InsHi, 2));
                                    }
                                    break;
                                case 2:
                                    if (arrTrace.arrTestItem[i + k].sTestName.Contains("隔离"))
                                    {
                                        TraceCom2max.Add(Math.Round(InsLo, 2));
                                        TraceCom2min.Add(Math.Round(InsHi, 2));
                                    }
                                    break;
                            }


                            if (arrTrace.arrTestItem[i + k].sFormatType == "DISP_DELA")
                            {
                                InsLo = InsLo * (float)Math.Pow(10, 9);
                                InsHi = InsHi * (float)Math.Pow(10, 9);
                            }

                            #endregion

                            #region 统一显示到界面

                            if (fMax_InsLo[k] < InsLo)
                                fMax_InsLo[k] = InsLo;

                            if (fMin_InsHi[k] > InsHi)
                                fMin_InsHi[k] = InsHi;

                            bool btemp = bTotalResult;

                            //bool bNowResult = DealResult(arrTrace.arrTestItem[i + k], InsLo, InsHi, ref bTotalResult);
                            bool bNowResult = DealResult(arrTrace.arrTestItem[i + k], fMax_InsLo[k], fMin_InsHi[k], ref bTotalResult);
                            bNowAllTraceResult &= bNowResult;



                            #region 重测1
                            if (IsReTest)
                            {
                                //if (!bNowResult && arrTrace.sTestFunction != "Continue")
                                //{//判断是否重测
                                //    //string sTips = "当前测试项测试失败，重试 Or 结束?";
                                //    FrmRetry frmTips = new FrmRetry();
                                //    DialogResult dr = frmTips.ShowDialog();
                                //    if (dr == DialogResult.No)
                                //    {//关闭
                                //        m_bNeedQuit = true;
                                //        return false;
                                //    }
                                //    else if (dr == DialogResult.Retry)
                                //    {//重试
                                //        k--;
                                //        bTotalResult = btemp;
                                //        continue;
                                //    }
                                //    else if (dr == DialogResult.Ignore)
                                //    {//继续
                                //    }
                                //}
                            }
                            #endregion

                            #endregion

                            #region 恢复IFBW等仪表特殊控制项
                            if (iLastIFBW[k] != 0)
                            {
                                if (!m_CInstrVNA.SetIFBandWidth(iLastIFBW[k]))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                            }
                            if (iLastSmooth[k] != 999)
                            {
                                if (!m_CInstrVNA.SetSmooth(Convert.ToString(iLastSmooth[k])))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                            }
                            if (iLastPoints[k] != 0)
                            {
                                if (!m_CInstrVNA.SetSweepPoints(iLastPoints[k]))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                            }
                            if (iLastPower[k] != 999)
                            {
                                if (!m_CInstrVNA.SetSweepPoints(iLastPower[k]))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                            }
                            #endregion
                        }
                        #endregion
                    }
                    while (!ctlObj.bQuit);
                }
                //}
                //while (!ctlObj.bQuit);
                if (!ctlObj.bCtrl)
                {//调度错误控制
                    MessageBox.Show("RCU调度失败!");
                    m_bNeedQuit = true;
                    return false;
                }
                #region 连续值判断
                if (m_testConfig[0].sCheckResult && arrTrace.iTraceArrNum != 1)
                {//判断测试结果是否一直保持不变
                    #region 调试
                    //double m1 = 60.02;
                    //double m2 = 60.01;
                    //double m3 = 60.02;
                    //double m4 = 60.02;
                    //double m5 = 60.02;
                    //double m6 = 60.02;
                    //TraceCom1max = new List<double>();
                    //TraceCom1max.Add(m1);
                    //TraceCom1max.Add(m2);
                    //TraceCom1max.Add(m3);
                    //TraceCom1max.Add(m4);
                    //TraceCom1max.Add(m5);
                    //TraceCom1max.Add(m6);
                    #endregion
                    //波形监控标准更改vswr=>0.03,iso=>0.2范围内变化 均视为无变化                   
                    double dVSWRSpec = 0.03d; double dISOSpec = 0.2d;
                    if (TraceCom0max.Count < 2)
                    {
                        {
                            MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                            bNowAllTraceResult = false;
                            bWavefromPass = false;
                        }
                    }
                    else
                    {
                        for (int n = 1; n < TraceCom0max.Count; n++)
                        {
                            if (Math.Abs(TraceCom0max[0] - TraceCom0max[n]) > dVSWRSpec)
                            {
                                break;
                            }
                            if (n == TraceCom0max.Count - 1)
                            {
                                MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                                bNowAllTraceResult = false;
                                bWavefromPass = false;
                            }
                        }
                    }

                    //for (int n = 0; n < TraceCom0min.Count - 1; n++)
                    //{
                    //    if (TraceCom0min[n] != TraceCom0min[n + 1])
                    //    {
                    //        break;
                    //    }
                    //    if (n == TraceCom0min.Count - 2)
                    //    {
                    //        MessageBox.Show("Trace0: 测得结果一直不变，请检查！");
                    //        bNowAllTraceResult = false;
                    //    }
                    //}
                    if (TraceCom1max.Count < 2)
                    {
                        MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                        bNowAllTraceResult = false;
                        bWavefromPass = false;
                    }
                    else
                    {
                        for (int n = 1; n < TraceCom1max.Count; n++)
                        {
                            if (Math.Abs(TraceCom1max[0] - TraceCom1max[n]) > dVSWRSpec)
                            {
                                break;
                            }
                            if (n == TraceCom1max.Count - 1)
                            {
                                MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                                bNowAllTraceResult = false;
                                bWavefromPass = false;
                            }
                        }
                    }

                    //for (int n = 0; n < TraceCom1min.Count - 1; n++)
                    //{
                    //    if (TraceCom1min[n] != TraceCom1min[n + 1])
                    //    {
                    //        break;
                    //    }
                    //    if (n == TraceCom1min.Count - 2)
                    //    {
                    //        MessageBox.Show("Trace1: 测得结果一直不变，请检查！");
                    //        bNowAllTraceResult = false;
                    //    }
                    //}
                    if (TraceCom2max.Count < 2)
                    {
                        MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                        bNowAllTraceResult = false;
                        bWavefromPass = false;
                    }
                    else
                    {
                        for (int n = 1; n < TraceCom2max.Count; n++)
                        {
                            if (Math.Abs(TraceCom2max[0] - TraceCom2max[n]) > dISOSpec)
                            {
                                break;
                            }
                            if (n == TraceCom2max.Count - 1)
                            {
                                MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                                bNowAllTraceResult = false;
                                bWavefromPass = false;
                            }
                        }
                    }
                    //for (int n = 0; n < TraceCom2min.Count - 1; n++)
                    //{
                    //    if (TraceCom2min[n] != TraceCom2min[n + 1])
                    //    {
                    //        break;
                    //    }
                    //    if (n == TraceCom2min.Count - 2)
                    //    {
                    //        MessageBox.Show("Trace2: 测得结果一直不变，请检查！");
                    //        bNowAllTraceResult = false;
                    //    }
                    //}
                }
                #endregion

                #region 重测2
                if (!bNowAllTraceResult)
                {//判断是否重测
                    FrmRetry frmTips = new FrmRetry(true);
                    DialogResult dr = frmTips.ShowDialog();
                    if (dr == DialogResult.No)
                    {//关闭
                        m_bNeedQuit = true;
                        m_bManualStop = true;
                        if (!bWavefromPass)
                            m_WavefromPass = bWavefromPass;
                        return false;
                    }
                    else if (dr == DialogResult.Retry)
                    {//重试
                        if (arrTrace.sTestFunction == "Continue")
                        {
                            string sRCUIndex = arrTrace.sPortA_RCU.Substring(0, arrTrace.sPortA_RCU.Length - GDefine.RCU_PORT_NAME.Length);

                            string sMaxAngle = "";
                            string sMinAngle = "";
                            Regex reg = new Regex(@"(\d+|-\d+)-(\d+|-\d+)");
                            var m = reg.Match(arrTrace.sPortA_Angle);
                            if (m.Success && m.Groups.Count == 3)
                            {
                                sMaxAngle = m.Groups[2].Value;
                                sMinAngle = m.Groups[1].Value;
                            }
                            else
                            {
                                MessageBox.Show("配置文件中角度设置错误,请检查!");
                                return false;
                            }
                            int iMinAngle = Convert.ToInt32(sMinAngle);
                            int iMaxAngle = Convert.ToInt32(sMaxAngle);
                            int iNeedAngle = m_isInitMaxAngle ? iMaxAngle : iMinAngle;

                            if (m_Instr.RCU_Type != 0)
                            {
                                FrmTips ctl_frm_message = new FrmTips("正在重设角度，请稍等！");
                                this.BeginInvoke(new ThreadStart(delegate
                                {
                                    ctl_frm_message.Show();
                                }));
                                setRCUIndex(sRCUIndex, iNeedAngle);
                                this.Invoke(new ThreadStart(delegate
                                {
                                    ctl_frm_message.Close();
                                }));
                            }
                            else
                            {
                                if (iMaxAngle != iMinAngle)
                                {
                                    m_dicRCUs[sRCUIndex].angle = -1;
                                }
                            }
                        }
                        bNowAllTraceResult = true;
                        bWavefromPass = true;
                        bTotalResult = bBeforResult;
                        tryNum--;
                        continue;
                    }
                    else if (dr == DialogResult.Ignore)
                    {//继续
                    }

                }
                #endregion
            }

            arrTrace.iTraceArrNum = 0;//测试完清空
            if (!bWavefromPass)
                m_WavefromPass = bWavefromPass;
            return true;
        }
        bool TestTrace(List<clsTestItem> lstTestItem, ref bool bTotalResult)
        {
            float InsLo, InsHi;
            bool bBeforResult = bTotalResult;
            bool bNowAllTraceResult = true;
            bool bWavefromPass = true;
            ImpCtrl ctlObj = new ImpCtrl() { bQuit = true, bCtrl = true };


            #region 设置4个trace
            if (!m_CInstrVNA.SetTraceCoun(4))
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
           
            /*--------------------------E5062A内部不会直接全部扫描出S参数, trig前必须设置好*/
            string[] sTestPortType = { "S11", "S22", "S21", "S12" };
            List<string> lstTestPortType = new List<string>(sTestPortType);
            for (int i = 0; i < sTestPortType.Length; i++)
            {
                if (!m_CInstrVNA.SetMeasType(i + 1, sTestPortType[i]))
                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            }
            /*--------------------------E5062A内部不会直接全部扫描出S参数, trig前必须设置好*/

            //if (!m_CInstrVNA.SetSweepType("LIN"))
            //    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            if (!m_CInstrVNA.SetSweepPoints(lstTestItem[0].sPoint))
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());

            #region 设置strat  stop
            float f1 = float.MaxValue;
            float f2 = float.MinValue;
            for (int i = 0; i < lstTestItem.Count; i++)
            {
                if (f1 > lstTestItem[i].f1)
                    f1 = lstTestItem[i].f1;
                if (f2 < lstTestItem[i].f2)
                    f2 = lstTestItem[i].f2;
            }
            if (!m_CInstrVNA.SetFrequency(f1, f2))
                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
            #endregion

            #endregion

            for (int tryNum = 0; tryNum < 1; tryNum++)
            {
                #region 端口调度
                if (lstTestItem[0].sTestFunction == "Continue")
                {
                    ctlObj.bQuit = false;
                    DelContinueSetRCUIndex del_continueSetRCUIndex = new DelContinueSetRCUIndex(continueSetRCUIndex);
                    string sRCUIndex = lstTestItem[0].sPortA_RCU.Substring(0, lstTestItem[0].sPortA_RCU.Length - GDefine.RCU_PORT_NAME.Length);

                    string sMaxAngle = "";
                    string sMinAngle = "";
                    Regex reg = new Regex(@"(\d+|-\d+)-(\d+|-\d+)");
                    var m = reg.Match(lstTestItem[0].sPortA_Angle);
                    if (m.Success && m.Groups.Count == 3)
                    {
                        sMaxAngle = m.Groups[2].Value;
                        sMinAngle = m.Groups[1].Value;
                    }
                    else
                    {
                        MessageBox.Show("配置文件中角度设置错误,请检查!");
                        return false;
                    }
                    int iMinAngle = Convert.ToInt32(sMinAngle);
                    int iMaxAngle = Convert.ToInt32(sMaxAngle);

                    #region 同端口分频测试
                    //clsTraceTest m_Continue_lsTraceTestedPrevious = new clsTraceTest();
                    //m_Continue_lsTraceTestedPrevious.arrTestItem[0] = new clsTestItem();
                    //m_Continue_lsTraceTestedPrevious.arrTestItem[0] = lstTestItem[0];
                    //m_Continue_lsTraceTestedPrevious.sPortA_RCU = lstTestItem[0].sPortA_RCU;
                    //m_Continue_lsTraceTested.Add(m_Continue_lsTraceTestedPrevious);
                    //if (m_Continue_lsTraceTested.Count > 1)
                    //{
                    //    foreach (clsTraceTest tra in m_Continue_lsTraceTested)
                    //    {
                    //        string sRCUIndex1 = tra.sPortA_RCU.Substring(0, tra.sPortA_RCU.Length - GDefine.RCU_PORT_NAME.Length);
                    //        if (tra.arrTestItem[0].sFreq != lstTestItem[0].sFreq && sRCUIndex1 == sRCUIndex)
                    //        {
                    //            int iIniAngle = m_isInitMaxAngle ? iMaxAngle : iMinAngle;
                    //            FrmTips ctl_frm_message = new FrmTips("正在设置端口" + sRCUIndex1 + "角度" + iIniAngle.ToString() + ",请稍等！");
                    //            if (m_Instr.RCU_Type != 0)
                    //            {
                    //                this.BeginInvoke(new ThreadStart(delegate
                    //                {
                    //                    ctl_frm_message.Show();
                    //                }));
                    //            }
                    //            continueSetRCUIndex(ctlObj, sRCUIndex, iIniAngle);
                    //            ctlObj.bQuit = false;
                    //            if (m_Instr.RCU_Type != 0)
                    //            {
                    //                this.BeginInvoke(new ThreadStart(delegate
                    //                {

                    //                    ctl_frm_message.Close();
                    //                    ctl_frm_message = null;
                    //                }));
                    //            }
                    //            break;
                    //        }
                    //    }
                    //}
                    #endregion

                    int iNeedAngle = !m_isInitMaxAngle ? iMaxAngle : iMinAngle;
                    if (m_dicRCUs[sRCUIndex].angle != iNeedAngle * 10)
                    {
                        if (m_Instr.RCU_Type == 0)
                        {//手动调度
                            this.Invoke(new ThreadStart(delegate
                            {
                                MessageBox.Show(sRCUIndex + " 开始手动调速，请准备(当点击确定后，请手动缓慢的转动角度)!");
                            }));
                        }

                        del_continueSetRCUIndex.BeginInvoke(ctlObj, sRCUIndex, iNeedAngle, null, del_continueSetRCUIndex);
                    }
                    else
                    {
                        ctlObj.bQuit = true;
                    }
                }
                #endregion

                List<double> TraceCom0min = new List<double>();
                List<double> TraceCom0max = new List<double>();
                List<double> TraceCom1min = new List<double>();
                List<double> TraceCom1max = new List<double>();
                List<double> TraceCom2min = new List<double>();
                List<double> TraceCom2max = new List<double>();

                #region 初始化
                int[] iLastIFBW, iLastPoints, iLastPower, iLastSmooth;
                float[] fMax_InsLo = new float[lstTestItem.Count];
                float[] fMin_InsHi = new float[lstTestItem.Count];
                iLastIFBW = new int[lstTestItem.Count];
                iLastPoints = new int[lstTestItem.Count];
                iLastPower = new int[lstTestItem.Count];
                iLastSmooth = new int[lstTestItem.Count];
                for (int tmp = 0; tmp < lstTestItem.Count; tmp++)
                {
                    iLastIFBW[tmp] = 0;
                    iLastPoints[tmp] = 0;
                    iLastPower[tmp] = 999;
                    iLastSmooth[tmp] = 999;
                    fMax_InsLo[tmp] = float.MinValue;
                    fMin_InsHi[tmp] = float.MaxValue;
                }
                #endregion
                //由于只有4个trace可以同时测所以进行分组循环//根据读值需要设置format，s21等读取值
                do
                {             
                    if (m_bNeedQuit) return false;
                    #region 统一trig  trig必须保证此次测试所有项目在同一角度
                    if (!m_CInstrVNA.BeforeTrig())
                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                    if (!m_CInstrVNA.TrigSingle())
                        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                    #endregion

                    for (int i = 0; i < lstTestItem.Count; i = i + 4)
                    {
                        this.BeginInvoke(new EventHandler(ShowText), i + "\r\n");
                        #region 统一设置
                        //for (int k = 0; k < 4; k++)
                        //{
                        //    if (i + k >= lstTestItem.Count)
                        //        break;
                        //    if (!m_CInstrVNA.SetMeasType(k + 1, lstTestItem[i + k].sTestPortType))
                        //        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        //    if (!m_CInstrVNA.SetDisplayFormat(k + 1, lstTestItem[i + k].sFormatType))
                        //        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        //    if (lstTestItem[i + k].sInstrCtrl != "")
                        //    {//额外的一些仪表控制，以便实现隔离度等测试
                        //        #region
                        //        //string[] arrCtrl = lstTestItem[i + k].sInstrCtrl.Split(';');
                        //        //for (int m = 0; m < arrCtrl.Length; m++)
                        //        //{
                        //        //    if (arrCtrl[m] == "")
                        //        //        continue;
                        //        //    string[] arrName = arrCtrl[m].Split('=');
                        //        //    if (arrName.Length < 2)
                        //        //    {
                        //        //        this.BeginInvoke(new EventHandler(ShowText), "无效的仪表控制项:" + arrCtrl[m]);
                        //        //        continue;
                        //        //    }
                        //        //    if (arrName[0] == "IFBW")
                        //        //    {
                        //        //        if (!m_CInstrVNA.GetIFBW(ref iLastIFBW[k]))
                        //        //        {
                        //        //            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        //        //        }
                        //        //        if (!m_CInstrVNA.SetIFBandWidth(Convert.ToInt32(arrName[1])))
                        //        //        {
                        //        //            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        //        //        }
                        //        //    }
                        //        //    else if (arrName[0] == "MAKRX")
                        //        //    {//根据频率，打mark点
                        //        //        if (!m_CInstrVNA.SetMark("MKR_FREQ", PIMFunction.FreqToHz(arrName[1]), k + 1))
                        //        //        {
                        //        //            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        //        //        }
                        //        //    }
                        //        //    else if (arrName[0] == "SMOOTH")
                        //        //    {//设定smooth
                        //        //        if (!m_CInstrVNA.GetSmooth(ref iLastSmooth[k]))
                        //        //        {
                        //        //            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        //        //        }
                        //        //        if (!m_CInstrVNA.SetSmooth(arrName[1]))
                        //        //        {
                        //        //            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        //        //        }
                        //        //    }
                        //        //    else if (arrName[0] == "POINTS")
                        //        //    {//设定POINT
                        //        //        if (!m_CInstrVNA.GetSweepPoints(ref iLastPoints[k]))
                        //        //        {
                        //        //            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        //        //        }
                        //        //        if (!m_CInstrVNA.SetSweepPoints(Convert.ToInt32(arrName[1])))
                        //        //        {
                        //        //            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        //        //        }
                        //        //    }
                        //        //    else if (arrName[0] == "POWER")
                        //        //    {//设定power
                        //        //        if (!m_CInstrVNA.GetPower(ref iLastPower[k]))
                        //        //        {
                        //        //            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        //        //        }
                        //        //        if (!m_CInstrVNA.SetPower(Convert.ToInt32(arrName[1])))
                        //        //        {
                        //        //            this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        //        //        }
                        //        //    }
                        //        //    else
                        //        //    {
                        //        //        this.BeginInvoke(new EventHandler(ShowText), "未知的仪表控制列:" + arrCtrl[m]);
                        //        //    }
                        //        //}
                        //        #endregion
                        //    }
                        //}
                        //if (!m_CInstrVNA.DisplayAutoScaleAll())
                        //    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        #endregion

                        #region 统一读值
                        for (int k = 0; k < 4; k++)
                        {
                            if (i + k >= lstTestItem.Count)
                                break;

                            if (!m_CInstrVNA.TraceSel(lstTestPortType.IndexOf(lstTestItem[i + k].sTestPortType) + 1))
                                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                            if (!m_CInstrVNA.SetDisplayFormatOnly(k + 1, lstTestItem[i + k].sFormatType))
                                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                            if (!m_CInstrVNA.DisplayAutoScaleAll())
                                this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                        

                            #region Mark
                            if (lstTestItem[i + k].sReport == "定点值")
                            {
                                if (!m_CInstrVNA.GetMarkYValue(out InsLo, k + 1))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                InsHi = 0;
                            }
                            else
                            {
                                //下面是mark取点法------------------------------------------------------
                                if (!m_CInstrVNA.SetMarkFuncDomState(true))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.SetMarkFuncDomRange(lstTestItem[i + k].f1, true))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.SetMarkFuncDomRange(lstTestItem[i + k].f2, false))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.SetMark("MKR_MAX", 0, 1))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.SetMark("MKR_MIN", 0, 2))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.GetMarkYValue(out InsLo, 1))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                if (!m_CInstrVNA.GetMarkYValue(out InsHi, 2))
                                {
                                    this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                                }
                                //-----------------------------------------------------------------------------*/
                            }
                            if (GDefine.IS_LOCAL)
                            {
                                InsLo = InsHi = lstTestItem[i + k].iTestIndex;
                            }

                            this.BeginInvoke(new EventHandler(ShowText), "trace_" + k + ": InsLo=" + InsLo + ", InsHi=" + InsHi + "\r\n");

                            switch (lstTestItem[i + k].sTestPortType)
                            {
                                case "S11":
                                    if (lstTestItem[i + k].sTestName.Contains("驻波"))
                                    {
                                        TraceCom0max.Add(Math.Round(InsLo, 2));
                                        TraceCom0min.Add(Math.Round(InsHi, 2));
                                    }
                                    break;
                                case "S22":
                                    if (lstTestItem[i + k].sTestName.Contains("驻波"))
                                    {
                                        TraceCom1max.Add(Math.Round(InsLo, 2));
                                        TraceCom1min.Add(Math.Round(InsHi, 2));
                                    }
                                    break;
                                case "S12":
                                case "S21":
                                    if (lstTestItem[i + k].sTestName.Contains("隔离"))
                                    {
                                        TraceCom2max.Add(Math.Round(InsLo, 2));
                                        TraceCom2min.Add(Math.Round(InsHi, 2));
                                    }
                                    break;
                            }


                            if (lstTestItem[i + k].sFormatType == "DISP_DELA")
                            {
                                InsLo = InsLo * (float)Math.Pow(10, 9);
                                InsHi = InsHi * (float)Math.Pow(10, 9);
                            }

                            #endregion


                            #region 统一显示到界面
                            //测试推送最差值
                            if (fMax_InsLo[i + k] < InsLo)
                                fMax_InsLo[i + k] = InsLo;
                            if (fMin_InsHi[i + k] > InsHi)
                                fMin_InsHi[i + k] = InsHi;
                            bool btemp = bTotalResult;
                            bool bNowResult = DealResult(lstTestItem[i + k], fMax_InsLo[i + k], fMin_InsHi[i + k], ref bTotalResult);
                            bNowAllTraceResult &= bNowResult;
                            #endregion

                            //Thread.Sleep(5000);
                            #region 恢复IFBW等仪表特殊控制项
                            //if (iLastIFBW[k] != 0)
                            //{
                            //    if (!m_CInstrVNA.SetIFBandWidth(iLastIFBW[k]))
                            //    {
                            //        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                            //    }
                            //}
                            //if (iLastSmooth[k] != 999)
                            //{
                            //    if (!m_CInstrVNA.SetSmooth(Convert.ToString(iLastSmooth[k])))
                            //    {
                            //        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                            //    }
                            //}
                            //if (iLastPoints[k] != 0)
                            //{
                            //    if (!m_CInstrVNA.SetSweepPoints(iLastPoints[k]))
                            //    {
                            //        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                            //    }
                            //}
                            //if (iLastPower[k] != 999)
                            //{
                            //    if (!m_CInstrVNA.SetSweepPoints(iLastPower[k]))
                            //    {
                            //        this.BeginInvoke(new EventHandler(ShowText), m_CInstrVNA.m_sbErr.ToString());
                            //    }
                            //}
                            #endregion
                        }
                        #endregion
                    }
                }
                while (!ctlObj.bQuit);

                if (!ctlObj.bCtrl)
                {//调度错误控制
                    MessageBox.Show("RCU调度失败!");
                    m_bNeedQuit = true;
                    return false;
                }
                #region 连续值判断
                if (m_testConfig[0].sCheckResult && lstTestItem[0].sTestFunction == "Continue")
                {//判断测试结果是否一直保持不变
                    #region 调试
                    //double m1 = 60.02;
                    //double m2 = 60.01;
                    //double m3 = 60.02;
                    //double m4 = 60.02;
                    //double m5 = 60.02;
                    //double m6 = 60.02;
                    //TraceCom1max = new List<double>();
                    //TraceCom1max.Add(m1);
                    //TraceCom1max.Add(m2);
                    //TraceCom1max.Add(m3);
                    //TraceCom1max.Add(m4);
                    //TraceCom1max.Add(m5);
                    //TraceCom1max.Add(m6);
                    #endregion
                    //波形监控标准更改vswr=>0.03,iso=>0.2范围内变化 均视为无变化                   
                    double dVSWRSpec = 0.03d; double dISOSpec = 0.2d;
                    //   MessageBox.Show(TraceCom0max.ToString());
                    if (TraceCom0max.Count < 2)
                    {
                        MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                        bNowAllTraceResult = false;
                        bWavefromPass = false;
                    }
                    else
                    {
                        for (int n = 1; n < TraceCom0max.Count; n++)
                        {
                            if (Math.Abs(TraceCom0max[0] - TraceCom0max[n]) > dVSWRSpec)
                            {
                                break;
                            }
                            if (n == TraceCom0max.Count - 1)
                            {
                                MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                                bNowAllTraceResult = false;
                                bWavefromPass = false;
                            }
                        }
                    }

                    //for (int n = 0; n < TraceCom0min.Count - 1; n++)
                    //{
                    //    if (TraceCom0min[n] != TraceCom0min[n + 1])
                    //    {
                    //        break;
                    //    }
                    //    if (n == TraceCom0min.Count - 2)
                    //    {
                    //        MessageBox.Show("Trace0: 测得结果一直不变，请检查！");
                    //        bNowAllTraceResult = false;
                    //    }
                    //}
                    if (TraceCom1max.Count < 2)
                    {
                        MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                        bNowAllTraceResult = false;
                        bWavefromPass = false;
                    }
                    else
                    {
                        for (int n = 1; n < TraceCom1max.Count; n++)
                        {
                            if (Math.Abs(TraceCom1max[0] - TraceCom1max[n]) > dVSWRSpec)
                            {
                                break;
                            }
                            if (n == TraceCom1max.Count - 1)
                            {
                                MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                                bNowAllTraceResult = false;
                                bWavefromPass = false;
                            }
                        }
                    }

                    //for (int n = 0; n < TraceCom1min.Count - 1; n++)
                    //{
                    //    if (TraceCom1min[n] != TraceCom1min[n + 1])
                    //    {
                    //        break;
                    //    }
                    //    if (n == TraceCom1min.Count - 2)
                    //    {
                    //        MessageBox.Show("Trace1: 测得结果一直不变，请检查！");
                    //        bNowAllTraceResult = false;
                    //    }
                    //}
                    if (TraceCom2max.Count < 2)
                    {
                        MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                        bNowAllTraceResult = false;
                        bWavefromPass = false;
                    }
                    else
                    {
                        for (int n = 1; n < TraceCom2max.Count; n++)
                        {
                            if (Math.Abs(TraceCom2max[0] - TraceCom2max[n]) > dISOSpec)
                            {
                                break;
                            }
                            if (n == TraceCom2max.Count - 1)
                            {
                                MessageBox.Show("测得结果一直不变(MAX)，请检查！", "波形监控");
                                bNowAllTraceResult = false;
                                bWavefromPass = false;
                            }
                        }
                    }
                    //for (int n = 0; n < TraceCom2min.Count - 1; n++)
                    //{
                    //    if (TraceCom2min[n] != TraceCom2min[n + 1])
                    //    {
                    //        break;
                    //    }
                    //    if (n == TraceCom2min.Count - 2)
                    //    {
                    //        MessageBox.Show("Trace2: 测得结果一直不变，请检查！");
                    //        bNowAllTraceResult = false;
                    //    }
                    //}

                }
                #endregion

                #region 重测2
                if (!bNowAllTraceResult)
                {//判断是否重测
                    FrmRetry frmTips = new FrmRetry(true);
                    DialogResult dr = frmTips.ShowDialog();
                    if (dr == DialogResult.No)
                    {//关闭
                        m_bNeedQuit = true;
                        m_bManualStop = true;
                        if (!bWavefromPass)
                            m_WavefromPass = bWavefromPass;
                        return false;
                    }
                    else if (dr == DialogResult.Retry)
                    {//重试
                        if (lstTestItem[0].sTestFunction == "Continue")
                        {
                            string sRCUIndex = lstTestItem[0].sPortA_RCU.Substring(0, lstTestItem[0].sPortA_RCU.Length - GDefine.RCU_PORT_NAME.Length);

                            string sMaxAngle = "";
                            string sMinAngle = "";
                            Regex reg = new Regex(@"(\d+|-\d+)-(\d+|-\d+)");
                            var m = reg.Match(lstTestItem[0].sPortA_Angle);
                            if (m.Success && m.Groups.Count == 3)
                            {
                                sMaxAngle = m.Groups[2].Value;
                                sMinAngle = m.Groups[1].Value;
                            }
                            else
                            {
                                MessageBox.Show("配置文件中角度设置错误,请检查!");
                                return false;
                            }
                            int iMinAngle = Convert.ToInt32(sMinAngle);
                            int iMaxAngle = Convert.ToInt32(sMaxAngle);
                            int iNeedAngle = m_isInitMaxAngle ? iMaxAngle : iMinAngle;

                            if (m_Instr.RCU_Type != 0)
                            {
                                FrmTips ctl_frm_message = new FrmTips("正在重设角度，请稍等！");
                                this.BeginInvoke(new ThreadStart(delegate
                                {
                                    ctl_frm_message.Show();
                                }));
                                setRCUIndex(sRCUIndex, iNeedAngle);
                                this.Invoke(new ThreadStart(delegate
                                {
                                    ctl_frm_message.Close();
                                }));
                            }
                            else
                            {
                                if (iMaxAngle != iMinAngle)
                                {
                                    m_dicRCUs[sRCUIndex].angle = -1;
                                }
                            }
                        }
                        bWavefromPass = true;
                        bNowAllTraceResult = true;
                        bTotalResult = bBeforResult;
                        tryNum--;
                        continue;
                    }
                    else if (dr == DialogResult.Ignore)
                    {//继续
                    }

                }
                #endregion
            }
            if (!bWavefromPass)
                m_WavefromPass = bWavefromPass;
            return true;
        }

        bool DealResult(clsTestItem arrTestItem, float InstrLow, float InstrHigh, ref bool bTotalResult)
        {
            bool ret = false;
            //生成显示值
            m_bRetestFlag = false;
            float fVal1, fVal2;//处理过的float值转为正数
            string sShow = PIMFunction.GetShowValue(arrTestItem.sReport, InstrLow, InstrHigh, out fVal1, out fVal2);

            //生成判断结果
            string sResult = "";
            bool bResult = PIMFunction.GetResult(arrTestItem.sFactSpec, fVal1, fVal2);
            if (bResult)
            {
                sResult = GDefine.ContentPass;
                ret = true;
            }
            else
            {
                sResult = GDefine.ContentFail;
                bTotalResult = false;
            }

            clsInsertRow aInsertRow = new clsInsertRow();
            aInsertRow.dgv = dgvTest;
            aInsertRow.iRow = arrTestItem.iTestIndex;
            aInsertRow.sValue = sShow;
            aInsertRow.sResult = sResult;
            this.BeginInvoke(new EventHandler(FillTestValue), aInsertRow);
            arrTestItem.result = ret;
            arrTestItem.sValue = sShow;
            return ret;
        }

        bool GetFreqRange(string strFreq, ref float f1, ref float f2)
        {
            //首先分解测试项的频率
            string[] arrSFreq = strFreq.Split('-');
            if (arrSFreq.Length != 2)
            {
                arrSFreq = strFreq.Split('～');
            }
            if (arrSFreq.Length != 2)
            {
                return false;
            }
            f1 = PIMFunction.FreqToHz(arrSFreq[0]);
            f2 = PIMFunction.FreqToHz(arrSFreq[1]);
            if (f1 > f2) { return false; }
            if (f1 == -1 || f2 == -1)
            {
                return false;
            }
            return true;
        }


        #endregion

        private void btnSet_Click(object sender, EventArgs e)
        {
            initDataConfig();
        }

        private void 数据特采ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_dtTestItem == null)
            {
                MessageBox.Show("请先加载配置!");
                return;
            }

            ClsDataUser aUser = new ClsDataUser();
            FrmUser frmlgn = new FrmUser(aUser, 1);
            frmlgn.Text = "需要管理员账号";
            frmlgn.ControlBox = true;
            frmlgn.cbTestItem.Enabled = false;
            if (frmlgn.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (!aUser.HavePower(clsPowerManage.POWER_FEAFTURES.ELEC_CONFIG_SELECT))
            {
                MessageBox.Show("权限不够!");
                return;
            }

            //FrmDataSpecial frmSpecial = new FrmDataSpecial();
            //frmSpecial.checkEnable.Checked = m_usrObj.aSpecial.bEnable;
            //frmSpecial.radioPIMTrue.Checked = m_usrObj.aSpecial.bNeedCheckPIM;
            //frmSpecial.radioPIMFalse.Checked = !m_usrObj.aSpecial.bNeedCheckPIM;
            //frmSpecial.nudMax.Value = Convert.ToDecimal(m_usrObj.aSpecial.fMaxVaule);
            //frmSpecial.nudMin.Value = Convert.ToDecimal(m_usrObj.aSpecial.fMinVaule);
            //if (frmSpecial.ShowDialog() == DialogResult.OK)
            //{
            //    m_usrObj.SetDataSpecial(frmSpecial.checkEnable.Checked,
            //                            frmSpecial.radioPIMTrue.Checked,
            //                            Convert.ToSingle(frmSpecial.nudMax.Value),
            //                            Convert.ToSingle(frmSpecial.nudMin.Value));
            //}
        }

        private void 重新登陆ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmUser frmlgn = new FrmUser(m_usrObj, 1);
            frmlgn.ControlBox = true;
            frmlgn.cbTestItem.Enabled = false;
            if (frmlgn.ShowDialog() == DialogResult.OK)
            {
                m_usrObj.sDarkroomNum = frmlgn.textBoxDarkroomNum.Text;
                toolStripStatusLabel2.Text = string.Format("员工号: {0}    姓名: {1}    账号类型: {2}",
                                                            m_usrObj.sUserID, m_usrObj.sUser, m_usrObj.sRemark);
                toolStripStatusLabel3.Text = string.Format("设备编号: {0}   管理部门: 质量", m_usrObj.sEquID);
            }
        }

        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmChangePwd frmpwd = new FrmChangePwd(m_usrObj);
            frmpwd.ShowDialog();
        }

        private void 电性能配置筛选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (m_dtTestItem == null)
            //{
            //    return;
            //}

            ClsDataUser aUser = new ClsDataUser();
            FrmUser frmlgn = new FrmUser(aUser, 1);
            frmlgn.Text = "需要管理员账号";
            frmlgn.ControlBox = true;
            frmlgn.cbTestItem.Enabled = false;
            frmlgn.textBoxUser2.Enabled = false;
            frmlgn.textPassword2.Enabled = false;
            frmlgn.isNeedUser2 = false;
            if (frmlgn.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (!aUser.HavePower(clsPowerManage.POWER_FEAFTURES.ELEC_CONFIG_SELECT))
            {
                MessageBox.Show("权限不够!");
                return;
            }

            FrmConfigSelect frmSelect = new FrmConfigSelect(aUser);
            frmSelect.ShowDialog();
        }

        private void 手动上传ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClsDataUser aUser = new ClsDataUser();
            FrmUser frmlgn = new FrmUser(aUser, 1);
            frmlgn.Text = "需要管理员账号";
            frmlgn.ControlBox = true;
            frmlgn.cbTestItem.Enabled = false;
            frmlgn.textBoxDarkroomNum.Enabled = false;
            frmlgn.textBoxDarkroomNum.Text = m_usrObj.sDarkroomNum;
            frmlgn.textBoxUser2.Enabled = false;
            frmlgn.textPassword2.Enabled = false;
            frmlgn.isNeedUser2 = false;
            if (frmlgn.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (!aUser.HavePower(clsPowerManage.POWER_FEAFTURES.ELEC_MANUAL))
            {
                MessageBox.Show("权限不够!");
                return;
            }


            FrmManualELEC frmManual = new FrmManualELEC(m_usrObj);
            frmManual.ShowDialog();
        }

        private void rCU配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!m_usrObj.HavePower(clsPowerManage.POWER_FEAFTURES.ELEC_CONFIG))
            {
                MessageBox.Show("权限不足！");
                return;
            }

            FrmConfigAntenna frmAnt = new FrmConfigAntenna(FrmConfigAntenna.TYPE_RCU);
            frmAnt.ShowDialog();
        }

        private void ctl_main_nudSpeed_ValueChanged(object sender, EventArgs e)
        {

        }

        private void fAD天线配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmTestTypeSelect frm = new FrmTestTypeSelect(m_isTestIso, m_isTestAmPh);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                m_isTestIso = frm.isTestIso;
                m_isTestAmPh = frm.isTestAmPh;
                // m_Procode = "";
            }
        }

        private void 设备调试ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!m_usrObj.HavePower(clsPowerManage.POWER_FEAFTURES.ELEC_DEBUG))
            {
                MessageBox.Show("权限不足！");
                return;
            }

            tb_Test.AppendText("正在连接仪表...\r\n");
            if (!ConnectionTest())
            {//如果连接失败弹出连接配置框
                tb_Test.AppendText("连接仪表失败.\r\n");
                return;
            }
            tb_Test.AppendText("连接仪表成功.\r\n");

            FrmSDebug frmDebug = new FrmSDebug(this.m_CInstrVNA, m_CLoadSwitch);
            frmDebug.ShowDialog();
        }

    }


    public class ValResult
    {
        public float Val;
        public int No;
        public float Val2;
        //public bool IsPass;
        public string sResult;
        public string strInfo;
    }

    [Serializable]
    public class clsTraceTest : BaseClone<clsTraceTest>
    {
        public string sBand;
        public string sPortA;
        public string sPortB;
        public float f1, f2;//要求同时测试的trace必须是同一个频率段
        public int iTraceArrNum = 0;
        public clsTestItem[] arrTestItem;
        public clsTraceTest()
        {
            arrTestItem = new clsTestItem[16];//创建16个数组 用于存储TRACE test
        }

        public string sPortA_Angle;
        public string sPortB_Angle;
        public string sPortA_RCU;
        public string sPortB_RCU;
        public string sTestFunction;

        public string sTestItem = ""; // 参数名称
        public string sTestPortType = ""; // 测试类型//S11,S21
        public string sFormatType = ""; // 格式化类型//DISP_LOGM

        public override clsTraceTest Clone()
        {
            return base.Clone();
            //MemoryStream memoryStream = new MemoryStream();
            //BinaryFormatter formatter = new BinaryFormatter();
            //formatter.Serialize(memoryStream, this);
            //memoryStream.Position = 0;
            //return (clsTraceTest)formatter.Deserialize(memoryStream);
        }
    }

    public class clsVNASetting
    {
        public int tracCount;
        public string fromat;
        public string meas;
        public int TracSel;

    }

    public class clsInsertRow
    {
        public DataGridView dgv;
        public int iRow;
        public string sValue;
        public string sResult;

    }

    public partial class BaseDlg : Form
    {
        public BaseDlg()
        {
        }

        public void MoveToRow(DataGridView dgv, int iFirstRow, int iCurRow)
        {
            if (dgv.RowCount == 0)
                return;

            if (iFirstRow < 0)
                iFirstRow = 0;
            if (iCurRow < 0)
                iCurRow = 0;
            if (iFirstRow >= dgv.RowCount)
                iFirstRow = dgv.RowCount - 1;
            if (iCurRow >= dgv.RowCount)
                iCurRow = dgv.RowCount - 1;
            dgv.Rows[iCurRow].Selected = true;
            if (dgv.Rows[iFirstRow].Visible == true)
                dgv.FirstDisplayedScrollingRowIndex = iFirstRow;
            if (dgv.Rows[iCurRow].Visible == true)
                dgv.CurrentCell = dgv.Rows[iCurRow].Cells[0];
        }

        protected bool NearlyEqual(string s1, string s2)
        {
            if (s1 == null || s2 == null)
            {
                return false;
            }
            int iMin = s1.Length;
            if (iMin > s2.Length)
                iMin = s2.Length;
            bool bSame = true;
            for (int i = 0; i < iMin; i++)
            {
                if (s1[i] != s2[i])
                {
                    bSame = false;
                    break;
                }
            }
            return bSame;

        }

        protected int ExistInList(string[] sList, string sAim)
        {
            int iFind = -1;
            for (int i = 0; i < sList.Length; i++)
            {
                if (NearlyEqual(sList[i], sAim))
                {
                    iFind = i;
                    break;
                }
            }
            return iFind;
        }

        protected string ShowRate(int iPassCount, int iFailCount)
        {
            float fRate = 0;
            if (iPassCount + iFailCount != 0)
            {
                fRate = (float)(iPassCount * 100.0 / (iPassCount + iFailCount));
            }
            return "成功记录 " + iPassCount + "; 失败记录" + iFailCount + "; 合格率" + fRate.ToString("#0.00") + "%";
        }

        protected string ShowRate(int iPassCount, int iMatchCount, int iFailCount)
        {
            float fRate = 0;
            if (iPassCount + iFailCount != 0)
            {
                fRate = (float)(iPassCount * 100.0 / (iPassCount + iFailCount));
            }
            string strMatchCount = "";
            if (iMatchCount >= 0)
                strMatchCount = "(未匹配记录" + (iMatchCount - iPassCount).ToString() + ")";
            return "成功记录 " + iPassCount + strMatchCount + "; 失败记录" + iFailCount + "; 合格率" + fRate.ToString("#0.00") + "%";
        }

        public bool GetPimFactResult(string factor, out float val, out string flag)
        {
            string header;
            float fac;
            float fac2;

            //header = factor.Substring(0, 2);

            Regex rx = new Regex(@"(\d+)\.(\d+)|(\d+)");
            MatchCollection ms = rx.Matches(factor);
            if (ms.Count >= 2)
            {
                fac = Convert.ToSingle(ms[0].Value);
                fac2 = Convert.ToSingle(ms[1].Value);
            }
            else
            {
                fac = Convert.ToSingle(ms[0].Value);
                fac2 = 999;
            }

            rx = new Regex(@"(\<)|(\>)|(\=)|(\±)|(\≤)|(\≥)|(\%)");
            ms = rx.Matches(factor);
            if (ms.Count >= 2)
            {
                header = ms[0].Value + ms[1].Value;
            }
            else if (ms.Count == 1)
            {
                header = ms[0].Value;
            }
            else
            {
                MessageBox.Show("内控指标不合法: " + factor);
                val = -10000;
                flag = "";
                return false;
            }

            val = fac * -1;
            flag = header;
            return true;
        }
    }
}
